【发布时间】: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