【发布时间】:2023-03-11 15:05:01
【问题描述】:
我正在努力降低嵌套属性。在Railscast 196 工作后,我尝试设置自己的应用程序来进行基本嵌套。用户可以创建寻宝游戏。每次狩猎都包含一系列任务(可以属于任何狩猎,而不仅仅是一个)。我得到了一点帮助 here 并试图从 similar issue 的帖子中学习,但我仍然卡住了。我已经折腾了好几个小时了,我撞到了一堵砖墙。
class HuntsController < ApplicationController
def index
@title = "All Hunts"
@hunts = Hunt.paginate(:page => params[:page])
end
def show
@hunt = Hunt.find(params[:id])
@title = @hunt.name
@tasks = @hunst.tasks.paginate(:page => params[:page])
end
def new
if current_user?(nil) then
redirect_to signin_path
else
@hunt = Hunt.new
@title = "New Hunt"
3.times do
#hunt = @hunt.tasks.build
#hunt = @hunt.hunt_tasks.build
hunt = @hunt.hunt_tasks.build.build_task
end
end
end
def create
@hunt = Hunt.new(params[:hunt])
if @hunt.save
flash[:success] = "Hunt created!"
redirect_to hunts_path
else
@title = "New Hunt"
render 'new'
end
end
....
end
使用这段代码,当我尝试创建一个新的狩猎时,我被告知没有方法“build_task”(它是未定义的)。因此,当我删除该行并使用上面注释掉的第二段代码时,我得到了下面的错误。
NoMethodError in Hunts#new
Showing /Users/bendowney/Sites/MyChi/app/views/shared/_error_messages.html.erb where line #1 raised:
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.errors
Extracted source (around line #1):
1: <% if object.errors.any? %>
2: <div id="error_explanation">
3: <h2><%= pluralize(object.errors.count, "error") %>
4: prohibited this <%= object.class.to_s.underscore.humanize.downcase %>
Trace of template inclusion: app/views/tasks/_fields.html.erb, app/views/hunts/_fields.html.erb, app/views/hunts/new.html.erb
当我使用在搜寻控制器中注释掉的第一段代码时,我收到一条错误消息,告诉我我的“新”方法有一个未初始化的常量:
NameError in HuntsController#new
uninitialized constant Hunt::Tasks
我已经束手无策了。关于我到底做错了什么有什么建议吗?或策略这是我的模型:
class Hunt < ActiveRecord::Base
has_many :hunt_tasks
has_many :tasks, :through => :hunt_tasks #, :foreign_key => :hunt_id
attr_accessible :name
validates :name, :presence => true,
:length => { :maximum => 50 } ,
:uniqueness => { :case_sensitive => false }
end
class Task < ActiveRecord::Base
has_many :hunt_tasks
has_many :hunts, :through => :hunt_tasks#, :foreign_key => :hunt_id
attr_accessible :name
validates :name, :presence => true,
:length => { :maximum => 50 } ,
:uniqueness => { :case_sensitive => false }
end
class HuntTask < ActiveRecord::Base
belongs_to :hunts # the id for the association is in this table
belongs_to :tasks
end
【问题讨论】:
-
嵌套属性有一种方式让你陷入困境,在走这条路之前探索使用表单类的选项(请参阅blog.codeclimate.com/blog/2012/10/17/… 中的第 3 点,了解一种可能的方法)跨度>
标签: ruby-on-rails rails-activerecord