2012-03-31 154 views
1

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

嘿再次本;)只是检查,你运行迁移HuntTasks,对不对?还请显示相关的控制器代码,thx,Michael。 – 2012-03-31 22:03:36

+1

顺便说一句,这个railscast对此很熟悉:http://railscasts.com/episodes/196-nested-model-form-part-1 – 2012-03-31 22:06:06

+0

你好!很高兴再次见到你!为了回答你的问题,是的,我已经运行了迁移。另外,我刚刚在帖子的主要部分发布了追捕控制器。是的,我正在开发Railscast 196,但是贝茨先生让它看起来非常简单,但我觉得这是一个漫长的艰难时刻。 – 2012-03-31 22:16:12

回答

0

你的榜样和railscast之间的主要区别是,你正在做许多对许多,而不是一对多(我觉得他调查有很多问题)。根据你所描述的,我想知道HuntTask模型是否有必要。一次狩猎的任务是否会在另一次追捕中被重新利用?假如是这样,那么看起来像你的答案就在这里:

Rails nested form with has_many :through, how to edit attributes of join model?

你必须修改你的新动作控制器做到这一点:

hunt = @hunt.hunt_tasks.build.build_task 

然后,你需要改变你的狩猎模式,包括:

accepts_nested_attributes_for :hunt_tasks 

并修改HuntTask模式,包括:

accepts_nested_attribues_for :hunt 
+0

我一直在玩这个设置,但没有太大的成功。我总是有关联错误'引发ArgumentError在HuntsController#新 \t \t没有相关发现名结束了'hunt_tasks'.' – 2012-04-01 16:06:57

+0

只是为了确认:该“accepts_nested_attributes_for:hunt_tasks”线被放置在两个后“的has_many:hunt_tasks”和' has_many:任务,通过......'在你的狩猎模型中? – Adam 2012-04-01 20:43:59

+0

是的,没错。 – 2012-04-01 21:12:13

相关问题