【问题标题】:Finding specific database entries when using nested attributes in RoR在 RoR 中使用嵌套属性时查找特定的数据库条目
【发布时间】:2015-05-04 16:14:05
【问题描述】:

我在我的 Ruby on Rails 应用程序 (4.0.2) 中使用嵌套属性,以便调查 has_many questions 并接受_nested_attributes_for questions 和 question belongs_to调查。

我遇到的问题是,当我只想查看属于特定调查的问题时,我得到一个“nil:NilClass”错误的“未定义方法“id”。另一方面,当我查看索引操作没有问题的所有问题时。

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

  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

我的调查/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

我还使用了一个名为 find_survey 的 before_action,如下所示:

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

谁能指出我正确的方向?

【问题讨论】:

  • @suslov 是的。我的调查控制器代码: class Survey :destroy accept_nested_attributes_for :questions , :reject_if => lambda { |a| a[:content].空白? } 范围 :sorted, lambda { order("questions.created_at DESC")}
  • 也许返回给定调查的问题应该是调查类的责任,然后你只需从控制器调用self.questions

标签: ruby-on-rails ruby nested-attributes


【解决方案1】:

NilClass 上的未定义方法是因为您的实例变量 @survey 为 nil,当您调用 Question.where(:survey_id =&gt; @survey.id).all 时,您会收到该错误。

如果您的关联设置正确,您应该能够运行@survey.questions 而不必在Questions 上执行搜索。这是 ActiveRecord rails 魔术的一部分。你不应该打电话给@survey.questions.all,因为这会返回 Question 类的所有实例,把它关掉,你应该很高兴。

至于为什么现在这对你不起作用,它可能只是一个订单问题——你在下面一行定义它之前调用了@survey

【讨论】:

  • 我不敢相信。控制器中的顺序。谢谢!
【解决方案2】:

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

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

所以也许你的“before_action”没有被调用?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 2011-08-14
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多