我正在製作一個項目,其中有任務組成尋找清道夫的項目。當用戶創建新的尋找時,我希望hunts/show.html.erb文件顯示尋找以及與該尋找相關的任務。但模型給我帶來麻煩。我已經設置了搜索模型,它接受任務模型的嵌套屬性。所以當用戶創建一個新的尋找時,她也會自動創建三個任務。我可以得到新的狩獵來保存,但我無法保存這些新的任務。這是我的模特。「接受嵌套屬性」實際上不接受模型中的屬性
什麼是缺失?我需要在HunTasks.rb文件中使用「attr accessible」語句嗎?
class Hunt < ActiveRecord::Base
has_many :hunt_tasks
has_many :tasks, :through => :hunt_tasks
accepts_nested_attributes_for :tasks, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
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
attr_accessible :name
validates :name, :presence => true,
:length => { :maximum => 50 } ,
:uniqueness => { :case_sensitive => false }
end
class HuntTask < ActiveRecord::Base
belongs_to :hunt # the id for the association is in this table
belongs_to :task
end
這裏就是我的亨特控制器的樣子:
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 = @hunt.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
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
嘿再次本;)只是檢查,你運行遷移HuntTasks,對不對?還請顯示相關的控制器代碼,thx,Michael。 – 2012-03-31 22:03:36
順便說一句,這個railscast對此很熟悉:http://railscasts.com/episodes/196-nested-model-form-part-1 – 2012-03-31 22:06:06
你好!很高興再次見到你!爲了回答你的問題,是的,我已經運行了遷移。另外,我剛剛在帖子的主要部分發布了追捕控制器。是的,我正在開發Railscast 196,但是貝茨先生讓它看起來非常簡單,但我覺得這是一個漫長的艱難時刻。 – 2012-03-31 22:16:12