我是一个经验丰富的java和C++开发人员,我正在try 了解Rails是如何工作的.

我得到以下代码:

respond_to do |format|
      if @line_item.save
        format.html { redirect_to store_url }
        format.js { render :json => @line_item, :mime_type => Mime::Type.lookup('application/json'), 
                :callback => 'javascriptFunction' }

我一直在搜索api,该api定义了我可以在format.js {}中传递的内容,但我找不到..

首先:什么样的语句是format.js,这是一个变量吗?

最重要的是:我可以将哪些属性传递到格式中.js{}?你能通过直连吗?我找了http://api.rubyonrails.org/多个

推荐答案

respond_to do |format|
  format.js # actually means: if the client ask for js -> return file.js
end

js here specifies a mime-type that the controller method would send back as a response;
Default Rails mime-types.
If you try also with format.yaml:

respond_to do |format|
  format.js
  format.yaml
end

这意味着您的控制器将根据客户端的请求返回ymljs

{} in terms of ruby is a block; If you don't specify any rails will try to render a default file from app/views/[contoller name]/[controller method name].[html/js/...]

# app/controllers/some_controller.rb
def hello
  respond_to do |format|
    format.js
  end
end

将寻找/app/views/some/hello.js.erb;//至少在Rails 2.3版中.

如果确实指定了块:

respond_to do |format|
    # that will mean to send a javascript code to client-side;
    format.js { render             
        # raw javascript to be executed on client-side
        "alert('Hello Rails');", 
        # send HTTP response code on header
        :status => 404, # page not found
        # load /app/views/your-controller/different_action.js.erb
        :action => "different_action",
        # send json file with @line_item variable as json
        :json => @line_item,
        :file => filename,
        :text => "OK",
        # the :location option to set the HTTP Location header
        :location => path_to_controller_method_url(argument)
      }

  end

Ruby-on-rails相关问答推荐

错误正在被ViewComponent、Ruby on Rails中吞噬

仅当未在带有ENV[';Dyno';]的Heroku问题上运行时才初始化Sidekiq Cron

通过激励控制器正确更新Turbo帧信源

确定当前太平洋时区是PST还是PDT

DateTime的最小数据提交格式

使用ImportMaps将HighLightJS添加到rails 7.1

使用嵌套属性时如何自动将父 ID 分配为外键?

我如何在不在 gemfile 中的 rake 任务中要求 gem?

如何从 New Relic 交易中获取 TraceId?

将日期时间转换为月、日和年?

设计:手动加密密码并直接存储

为什么使用 HTTP PUT 和 DELETE 方法而不是 POST?

Rails 模型:您将如何创建一组预定义的属性?

具有条件的列的计数器缓存?

将根 url 重定向到 Rails 应用程序中的其他位置

Redis 引发需要 NOAUTH 身份验证错误,但没有设置密码

如何编写 Capybara 断言来判断按钮的存在及其启用或禁用状态?

按周/月/等和 ActiveRecord 分组?

ruby 方法名称中的变量

让 bundler 为不同的平台使用不同的 gem