在 RoR 中使用嵌套属性时查找特定的数据库条目

Finding specific database entries when using nested attributes in RoR

我在 Rails 应用程序 (4.0.2) 上的 Ruby 中使用嵌套属性,这样调查 has_many 问题和 accepts_nested_attributes_for 问题和问题 belongs_to调查。

我 运行 遇到的问题是,当我只想查看属于特定调查的问题时,我得到 "undefined method "id" for nil:NilClass" -错误。另一方面,当我查看索引操作没有问题的所有问题时。

我的问题控制器索引操作:

  def index
     @questions = Question.where(:survey_id => @survey.id).all # if instead I use @questions = Question.all it works fine, but is not what I want.
     #@questions = @survey.questions.all
     @surveys = Survey.all
     @survey = Survey.first
 end

我的 surveys/index.html.erb 页面:

  <%= link_to("questions", { :controller => 'questions', :survey_id => survey.id }, :class => 'btn btn-xs') do %>
        <%= glyph 'th-list' %>
  <%- end -%>

我的问题模型:

 class Question < ActiveRecord::Base
   belongs_to :survey
   scope :sorted, lambda { order("questions.created_at ASC")}
 end

我还使用了一个 before_action,我称之为 find_survey,它看起来像这样:

def find_survey
  # If in each action calling this method (find_survey) has :survey_id sent
  if params[:survey_id]
    # We will then go to the database and look for (and find) :survey_id and set that to @survey. 
    @survey = Survey.find(params[:survey_id])
  end
end

有人能指出我正确的方向吗?

根据您发布的错误,@survey 可能 nil 在这一行中:

@questions = Question.where(:survey_id => @survey.id).all

所以也许您的 "before_action" 没有被调用?

NilClass 上的未定义方法是因为您的实例变量 @survey 为 nil,而当您调用 Question.where(:survey_id => @survey.id).all 时出现该错误。

如果您的关联设置正确,您应该能够 运行 @survey.questions 而不必在 Questions 上执行搜索。这是 ActiveRecord rails 魔法的一部分。您不应该调用 @survey.questions.all,因为这将 return 问题的所有实例 class,将其关闭,您应该可以开始了。

至于为什么这现在对您不起作用,这可能只是一个顺序问题 — 您在下面的行中定义它之前先调用 @survey