2016-11-29 54 views
0

我試圖保存我的模型,但未能保存它。Rails has_many通過保存失敗

#starship.rb 

class Starship < ApplicationRecord 
    has_many :crew_members,inverse_of: :starship 
    accepts_nested_attributes_for :crew_members 

    has_many :holodeck_programs,inverse_of: :starship 
    accepts_nested_attributes_for :holodeck_programs 
end 

#crew_member.rb 

class CrewMember < ApplicationRecord 
    belongs_to :starship 
    accepts_nested_attributes_for :starship 
    has_many :holodeck_programs,through: :starship 
end 

#holodeck_program.rb 

class HolodeckProgram < ApplicationRecord 
    belongs_to :starship 
    belongs_to :crew_member 
end 

#controller 

def create 
    #Starship,CrewMember and HolodeckProgram are new via CrewMember.new 
    @crew_member = CrewMember.new(crew_member_params) 
    @crew_member.save 
    . 
    . 
end 
    . 
    . 
private 
def crew_member_params 
    params.require(:crew_member).permit(:name,:division,:starship_id, 
    starship_attributes: [:name,:id, 
    holodeck_programs_attributes: [:title,:starship_id,:crew_member_id]]) 
end 

因爲在holodeck_programs_attributes沒有crew_member_id,驗證錯誤發生。

我如何處理它在crew_member.rb通過crew_member因爲:

我不能使用inverse_of:?

回答

0

實際上,您可以創建任意數量的crew_members,holodeck_programs,同時創建一個星艦。

但你要創建許多飛船,holodeck_programs單個crew_members,看看

def crew_member_params 
    params.require(:crew_member).permit(:name,:division,:starship_id, 
    starship_attributes: [:name,:id, 
    holodeck_programs_attributes: [:title,:starship_id,:crew_member_id]]) 
end 

所以,你需要改變創造,

def create 
    @starship = Starship.new(star_ship_params) 
    @starship.save 
end 

和crew_member_params到

def star_ship_params 
    params.require(:star_ship).permit(<attributes of star_ship>, holodeck_programs_attributes: [<attributes of holodeck_programs>], crew_members_attributes: [<attributes of crew_members>]) 
end 

還要確保您已完成視圖acc中的所有更改ordingly

有關嵌套屬性及其用法的更多信息,請查看:NestedAttributes

+0

我不明白你的回答'''@starship = Starship.new(star_ship_params) @ crew_member.save'''與@starship和@crew_member –

+0

沒有關係其實這是我犯的一個錯誤。我現在糾正了它。 –

+0

謝謝,但你的答案是爲了節省星艦,我想同時保存船員和星艦和HolodeckProgram。但是,如何在保存前獲取crew_member_id? –