我试图保存我的模型,但未能保存它。
#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,因此会发生验证错误。
我不能使用inverse_of :: crew_member因为在crew_member.rb中通过
我该如何处理?
答案 0 :(得分:0)
实际上,您可以在创建星舰时创建任意数量的crew_members,holodeck_programs。
但是你正在尝试为一个机组成员创建许多星舰,holodeck_programs,查看
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
并确保您已相应地在视图中完成所有更改
请查看:{{3}},了解有关嵌套属性及其用法的更多信息。