【问题标题】:how to access data with has_many :through relation如何使用 has_many 访问数据:通过关系
【发布时间】:2012-09-19 23:26:26
【问题描述】:

您好,我有三种模型:公司、计划和订阅,并具有以下关联

    class Company < ActiveRecord::Base
      has_one :plan, :through => :subscriptions
      has_many :subscriptions
    end

    class Subscription < ActiveRecord::Base
      belongs_to :plan
      belongs_to :company
    end

   class Plan < ActiveRecord::Base
      has_many :subscriptions
      has_many :companies, :through => :subscriptions
    end

我的申请计划“A”和计划“B”中有两个计划。计划“A”是免费的,“B”是收费的。现在我想让公司注册计划“A”和注册计划“B”的公司。
我想在我的模型中使用这些数据,我知道它们绝对是获得所有这些的简单方法,但是 我用过的每样东西都没有给我正确的数据。任何帮助都将不胜感激。

【问题讨论】:

    标签: ruby-on-rails-3 associations has-many-through


    【解决方案1】:

    您需要通过关联插入新记录。这是一个可能有帮助的相关链接。 how to add records to has_many :through association in rails

    但是伪代码就像

    1. You have a company object
    2. you will have company.subscriptions
    3. Insert new Plan objects in company.subscriptions
    4. Save the data.
    

    如果你仍然遇到问题,我会尝试添加一些代码示例。

    【讨论】:

    • 感谢先生的回答。但我在注册时保存了公司计划和订阅。计划值通过链接作为参数传递,然后将自动保存在订阅表中。请添加一个示例代码
    • 好的,我会的。那个周末好 :)
    【解决方案2】:

    让公司注册计划“A”和注册计划“B”的公司。 以计划的对象,然后通过以下关系代码,您将获得公司的数量。 这是加入概念。 例如。 @plan 是计划“A”的对象。 然后@plan.companies.count。

    我建议使用“多态关联”的概念。

    【讨论】:

      猜你喜欢
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多