0

In Rails 3, using the new respond_to and respond_with constructs, I do this:

class SurveysController < ApplicationController
  respond_to :html

  def survey
    @program_id = params[:program_id]
    @participant_id = params[:participant_id]
    respond_with [@program_id, @participant_id]
  end
end

When the view is displayed (survey.html.erb) the variables program_id, @participant_id are both properly set up. However, if I omit them from the respond_with, as follows:

class SurveysController < ApplicationController
  respond_to :html

  def survey
    @program_id = params[:program_id]
    @participant_id = params[:participant_id]
    @foo = "foo"
    respond_with @foo
  end
end

The same two instance variables are still visible in the view. In other words, all instance variables from the action are made available from within the view.

Question: why should I put instance variables on the respond_to line?

4

1 回答 1

1

您是正确的,您在操作方法中设置的任何实例变量都可以在相应的视图中访问。在您的情况下,您只是将 id 设置为实例变量,而不是实际资源(即@survey = Survey.find_by_program_id(params[:program_id])

respond_with 将为您提供的资源发送具有适当格式的响应......因此您不会将 respond_with 用于所有实例变量,而是将其用于资源。如果您添加了其他格式,例如:json,那么如果请求是 for survey.jsonrespond_with则会将您的@survey资源转换为适当的 json 格式。

respond_to :html, :json
def survey
  @program_id = params[:program_id]
  @participant_id = params[:participant_id]
  @survey = Survey.find_by_program_id(params[:program_id])
  respond_with @survey
end

不确定这对您是否完全有意义,但这篇文章可能会有所帮助。

于 2012-11-07T20:51:34.607 回答