我在与rails 4的关联中创建记录时遇到了麻烦。它基本上是Entry和Author之间的关联,中间有一个名为AuthorsEntry的连接表。架构如下:
class Entry < ActiveRecord::Base
validates :name, presence: true
validates :from, presence: true
validates :to, presence: true
belongs_to :event
has_many :authors, through: :authors_entry
has_many :authors_entry
class AuthorsEntry < ActiveRecord::Base
validates :author, presence: true
validates :entry, presence: true
belongs_to :author
belongs_to :entry
end
class Author < ActiveRecord::Base
belongs_to :event
has_many :entries, through: :authors_entry
has_many :authors_entry
validates :name, presence: true
validates :event, presence: true
end
在我的program_entries_controller.rb
我有以下方法:
def create
@program_entry = Entry.new(program_entry_params)
author_ids_params.each do |id|
@program_entry.authors << AuthorsEntry.build(author_id: id)
end
@program_entry.event = @event
if @program_entry.save
flash[:notice] = t(:program_entry_created_successfully)
redirect_to organizer_event_program_entry_path(@event, @program_entry)
else
render :new
end
end
def program_entry_params
params.require(:program_entry).permit(
:name, :abstract, :'from(1i)', :'from(2i)', :'from(3i)',
:'from(4i)', :'from(5i)', :'to(1i)', :'to(2i)', :'to(3i)', :'to(4i)',
:'to(5i)'
)
end
def author_ids_params
params.require(:program_entry).permit(:author_ids => [])
end
我已经将作者保存在我的数据库中,创建操作应该只为Entry模型和关联(authors_entry)表添加新记录。但是当我尝试保存条目时,它总是在authors_entry上返回“is_invalid”。
答案 0 :(得分:2)
连接表应命名为AuthorEntries
以遵循rails约定。