我正在开展一个项目,其中有一些任务组成了寻宝者。当用户创建新的搜索时,我希望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
这是我的Hunt控制器的样子:
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
答案 0 :(得分:0)
你的例子与railscast之间的主要区别在于你做的是多对多而不是一对多(我认为他的调查有很多问题)。根据您的描述,我想知道HuntTask模型是否必要。一次狩猎的任务是否会在另一场狩猎中被重复使用?假设它们是,那么看起来你的答案就在这里:
Rails nested form with has_many :through, how to edit attributes of join model?
您必须在控制器中修改新操作才能执行此操作:
hunt = @hunt.hunt_tasks.build.build_task
然后,您需要更改您的Hunt模型以包含:
accepts_nested_attributes_for :hunt_tasks
修改您的HuntTask模型以包含:
accepts_nested_attribues_for :hunt