【发布时间】:2014-08-25 20:33:58
【问题描述】:
我的应用有 2 个需要多对多关系的模型。我最初尝试使用 has_and_belongs_to_many 但它不起作用。在互联网上搜索后,我确信这不是我需要的。所以,我通过方法切换到了 has_many 。但是,这也不起作用。我现在对问题是什么感到不知所措。我已经把它撕了很多次,教程一个接一个地尝试,但无济于事。
我尝试连接的模型是 Message 和 Author。在我最近的尝试中,我创建了一个名为 Authoring 的连接模型(带有相应的表)。这是我的代码:
message.rb
has_many :authorings
has_many :authors, through: :authorings
作者.rb
has_many :authorings
has_many :messages, through: :authorings
authoring.rb
belongs_to :message
belongs_to :author
messages_controller.rb
def messages_params
params.require(:message).permit(:title, :summary, :date, :duration, :youversion, :hours, :minutes, :seconds, :authors)
end
我的消息表单:
<%= f.label :speakers %><br />
<%= collection_select(:authors, :authors, Author.all, :id, :name, {}, {:multiple => true, :size => 10}) %>
当我创建一条新消息时,它会显示在日志中:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"OcLeke/eRRzwApoMSgQF81kBCm7TaGxW1PoVAUgEcvo=", "message"=>{"title"=>"Test1", "summary"=>"This is my test summary.", "date(2i)"=>"8", "date(3i)"=>"25", "date(1i)"=>"2014", "date(4i)"=>"01", "date(5i)"=>"00", "hours"=>"0", "minutes"=>"58", "seconds"=>"52", "youversion"=>""}, "authors"=>{"authors"=>["", "1"]}, "commit"=>"I'm Finished", "id"=>"1"}
表单显然可以识别表单中的作者,但不会将它们保存在数据库中。我的断线是什么?请帮忙!!!
谢谢!
【问题讨论】:
标签: activerecord ruby-on-rails-4 many-to-many has-many-through