ネストされた属性を取得するのは難しいです。 Railscast 196の作業から、私は基本的なネスティングを行う自分のアプリケーションをセットアップしようとしました。ユーザーはスカベンジャー狩りを作成できます。各狩りは、一連の作業で構成されています(いずれかの狩猟に属することができます)。私は少し助けを受けたhereとsimilar issueとの投稿から学ぶことを試みたが、私はまだ固執している。私は何時間もハッキングしていて、レンガの壁にぶつかった。このコードではRails:モデルはネストされた属性を受け入れますが、コントローラは気にしないようです。
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」がないことを聞いています。だから私はその行を削除し、上記のコメントのコードの2番目のビットを使用すると、私は以下のエラーが表示されます。
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
Iを私のウィットの終わりで。正確に何が間違っているのかに関する提案はありますか?それともここでの戦略は、私のモデルです:
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
ネストされた属性は、道路を噛み砕く方法を持っています。その道を進む前にフォームクラスを使用するオプションを探します(http://blog.codeclimate.com/blog/2012/10/17のポイント3を参照)。/7-ways-to-decompose-fat-activerecord-models /これに可能なアプローチの1つ) – bbozo