2012-03-31 96 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