我正在制作一个项目,其中有任务组成寻找清道夫的项目。当用户创建新的寻找时,我希望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