【问题标题】:Can we have multiple join tables for the same pair of tables?我们可以为同一对表创建多个连接表吗?
【发布时间】:2016-12-08 08:40:44
【问题描述】:

我有两个表:offers 和 tests。

但我需要三个连接表,例如 offer_tests_1、offers_tests_2 和 offer_tests_3。这是因为一项业务要求,一个报价可以包含三个测试组合(包)。

我们可以在 Rails 中做到这一点吗?对于一个连接表,我可以使用模型中的 has_and_belongs_to_many 关联和视图中的 f.collection_select 标记,使用 :multiple => true。

最坏的情况,我可以用相同的数据设置三个表tests_1、tests_2 和tests_3。我想避免这种情况。

【问题讨论】:

    标签: ruby-on-rails has-and-belongs-to-many jointable


    【解决方案1】:

    是的,你可以 定义关系时,您可以在模型中执行此操作。像这样。

    在模型 Offer.rb 中

    has_many :offers_tests_1
    has_many :offers_tests_2
    has_many :tests, through: :offers_tests_1
    has_many :tests, through: :offers_test_2
    

    在模型Tests.rb中

    has_many :offers_tests_1
    has_many :offers_tests_2
    has_many :offers, through: :offers_tests_1
    has_many :offers, through: :offers_test_2
    

    享受

    【讨论】:

    • 我正在使用这种方法,但视图仍然是一个问题。我有以下 - <%= form_for(@offer) do |f| %> <%= f.fields_for :offers_tests_1 do |ot| %> <%= ot.collection_select(:test_id, Test.all, :id, :property, {include_hidden: false}, :multiple => true) %> <% end %> <% end %> 我的错误是 - 字段没有默认值
    • 不是 fields_for :offers_tests_1 使用 fields_for :tests
    • 我在 collection_select 中的哪个位置指定关联?我有三个关联和三个连接表。如果我使用 fields_for :tests,Rails 会将数据插入到第三个连接表中。
    猜你喜欢
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多