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:?
我不明白你的回答'''@starship = Starship.new(star_ship_params) @ crew_member.save'''與@starship和@crew_member –
沒有關係其實這是我犯的一個錯誤。我現在糾正了它。 –
謝謝,但你的答案是爲了節省星艦,我想同時保存船員和星艦和HolodeckProgram。但是,如何在保存前獲取crew_member_id? –