【问题标题】:Rails association modelsRails 关联模型
【发布时间】:2014-02-16 02:27:25
【问题描述】:

我正在尝试为我的模型建立正确的关联,但无法弄清楚。

我有 3 个模型,BatManufacturerReview。这是我的模型:

class Bat < ActiveRecord::Base
  has_many :reviews
  has_one :manufacturer
end

class Manufacturer < ActiveRecord::Base
  has_many :bats
end

class Review < ActiveRecord::Base
  belongs_to :bat
end

在 Review 模型中,它有一个 bat_idmanufacturer_id 字段。在 Bat 模型中,它有一个 manufacturer_id 字段。

我正在尝试将制造商模型正确链接到蝙蝠模型。我查看了http://guides.rubyonrails.org/association_basics.html#self-joins,但我不确定这是我需要的关系类型。

这是正确的还是我遗漏了什么?

【问题讨论】:

    标签: ruby-on-rails model associations


    【解决方案1】:

    正如您在自联接文档中所见,自联接用于将模型与自身联接。您不需要这样做,因为制造商在任何方面都不属于另一家制造商(至少,不是从您的描述中可以看出)。

    此外,您的 Review 模型不需要链接到 Manufacturer 模型(也就是说,您不需要在 Review 模型上使用 manufacturer_id

    你的蝙蝠模型应该有belongs_to :manufacturer,因为它属于制造商,它没有。您可以在此处阅读有关 belongs_tohas_one 的更多信息:http://guides.rubyonrails.org/association_basics.html#choosing-between-belongs-to-and-has-one

    您所需要的只是您的 Bat 表上的 manufacturer_id 和 Review 表上的 bat_id。然后你就可以使用 Rails 的所有魔法了,比如

    bat.manufacturer # get the manufacturer of a bat
    manufacturer.bats # get all the bats from a manufacturer
    bat.reviews # get all the reviews for a bat
    

    显然您需要创建迁移以将字段添加到数据库中,例如

    rails generate migration add_manufacturer_id_to_bat manufacturer_id:integer
    rails generate migration add_bat_id_to_review bat_id:integer
    rake db:migrate
    

    【讨论】:

    • 好的,谢谢,这是有道理的。我在我的评论表中使用了manufacturer_id,因为它允许我设置一个包含两个下拉选项的表单。在一个下拉列表中,用户选择制造商,在另一个下拉列表中选择球棒名称。我想使用 javascript(基于chasepursley.com/…)来实现良好的 UI。最好仅根据动态下拉列表将 bat_id 存储在评论表中,但我无法弄清楚。 (这就是为什么我有 bat_id 和制造商 ID)
    • 我一直在试图找出如何解决这个问题stackoverflow.com/questions/21690556/…
    • 我无法让bat.manufacturer 工作,只有bat.manufacturer_id 会显示整数。
    • 您确定您的关联正确吗?例如,belongs_to :manufacturer 在 Bat 模型中,has_many :bats 在 Manufacturer 模型中?
    • @ravensfan55222 不幸的是,我没有足够的信息来告诉你问题出在哪里,因为 Rails 关联确实有效,它们所需要的只是数据库中的一个字段和正确的关联在模型中设置。通常我不这样做,但我已经为您设置了一个演示应用程序,它演示了关联的使用。您可以在 Heroku 上查看它:secret-bayou-5954.herokuapp.com,您会注意到蝙蝠旁边的制造商名称。在此处查看源代码:github.com/levymetal/stackoverflow-bats。将此与您的进行比较,看看差异在哪里。
    【解决方案2】:

    因为您的制造商有很多蝙蝠,您的蝙蝠属于一个制造商,所以我认为将has_one :manufacturer 更改为belongs_to :manufacturer 将解决您的问题。

    【讨论】:

      【解决方案3】:

      将你的蝙蝠类别更改为

      class Bat < ActiveRecord::Base
        has_many   :reviews
        belongs_to :manufacturer
      end
      

      【讨论】:

      • 这个答案是正确的。操作员说蝙蝠“有一个制造商”,而制造商“有很多蝙蝠”。每个has_manyhas_one 都需要另一个模型上的belongs_to 对应项。模型关联的两端不能有两个 has_*
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 2018-10-15
      • 2011-09-22
      • 2012-05-23
      相关资源
      最近更新 更多