【问题标题】:Rails 4 many to many relationshipRails 4 多对多关系
【发布时间】: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


    【解决方案1】:

    authors 记录没有被创建,因为控制器期望 authors 出现在 params 哈希中的 message 键的值中,但是如果您注意到 params 中的哈希日志

    参数:{"utf8"=>"✓", "authenticity_token"=>"OcLeke/eRRzwApoMSgQF81kBCm7TaGxW1PoVAUgEcvo=", "message"=>{...}, "authors"=>{...}, "commit"=>"I'm Finished", "id"=>"1"}

    您会看到 authorsparams 哈希中作为一个完全独立的键出现,这就是它被忽略的原因。

    您需要做的是将作者与form 对象相关联,而不是使用collection_select,您需要使用f.collection_select,如下所示。将f.collection_select中的第一个参数指定为:author_ids

    <%= f.collection_select(:author_ids, Author.all, :id, :name, {}, {:multiple => true, :size => 10}) %>
    

    由于您指定了:multiple =&gt; true 选项,您将在params 哈希中收到authors 作为Array。您需要在 message_params 方法中允许 author_ids 作为 Array

    def messages_params
        params.require(:message).permit(:title, :summary, :date, :duration, :youversion, :hours, :minutes, :seconds, :author_ids => [])
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      相关资源
      最近更新 更多