【问题标题】:Rails 3.1 Advanced Has_many and belongs_to model joinsRails 3.1 高级 Has_many 和 belongs_to 模型连接
【发布时间】:2012-01-08 02:36:42
【问题描述】:

我有两张桌子。项目和供应商。物品由供应商出售。所以 Item belongs_to :vendor 和 Vendor has_many :items。效果很好。

但是,物品并不总是由销售它们的供应商制造,但有时它们是。所以我的项目表中有一个名为“manufacturer_id”的新列。我没有生成一个名为 Manufacturer 的新模型,它与 Vendor 完全相同,而是尝试做一个复杂的 has_many 和 belongs_to 来定义制造商。

看这里:

class Item < ActiveRecord::Base
  belongs_to :vendor
  belongs_to :manufacturer, :class_name => "Vendor", :foreign_key => "manufacturer_id"
end

class Vendor < ActiveRecord::Base
  has_many :items
  has_many :manufactured_items, :class_name => "Item", :foreign_key => "manufacturer_id"
end

在项目表中填充manufacturer_id 可以在创建命令上按预期工作:

Item.create(:manufacturer => Vendor.find_by_abbrev("INV"))

而且我什至可以得到制造商作为操作

item.manufacturer

返回:

<Vendor:0x007ff06684e398>

但是:

item.manufacturer.name

由于硬异常而完全失败,我收到错误:

undefined method `name' for nil:NilClass

运行

debug item.manufacturer

给予

--- !ruby/object:Vendor
attributes:
  id: 181
  name: Invitrogen
  website: http://www.invitrogen.com/
  created_at: 2012-01-08 01:39:07.486375000Z
  updated_at: 2012-01-08 01:39:07.486375000Z
  abbrev: INV

所以 item.manufacturer.name 应该返回上面那个供应商对象的名称,供应商:0x007ff06684e398。

我在这里做错了什么?

此外,一旦我得到这个工作,我希望能够类似地调用:

vendor.manufactured_items

获取具有该供应商的manufacturer_id的所有项目。有没有一种简单的方法也可以做到这一点?

我最后的努力可能涉及到必须做的事情:

制造商 = Vendor.new(item.manufacturer)

但这似乎完全错误,并且与此处的 rails 文档背道而驰: http://guides.rubyonrails.org/association_basics.html#self-joins

请帮忙!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    好的,我实际上已经为您和posted it on GitHub 构建了一个演示 Rails 3.1 项目。我在README 文件中包含了控制台输出,以证明item.seller.name 和item.manufacturer.name 之类的调用以及vendor.sold_items.first.manufacturer.name 之类的往返调用可以让您获得制造商的名称例如,特定供应商的第一个售出商品。

    我认为,正如您所指出的,问题的根源在于 vendor 和 manufacturer 在所有意图和目的上都是相同的。出于这个原因,我将它们简单地组合到 Vendor 类中,并以这样一种方式设置外键关系,它应该按照我认为你想要的方式工作。

    特别是,您应该注意README 文件,该文件包含我运行的控制台会话输出以显示它正常工作。您还需要查看这两个模型类以及它们的关联是如何定义的,以及 spec/factories.rb 文件了解它如何设置假数据库数据(我在下面包含了这些)。

    今天早上重新阅读您的问题时,我不确定您做错了什么,但您可能会将其归结为您在某处的联想中的一个细微错误。这可能是您真的接近但并不完全接近的情况。 :D

    以下是代码中的一些片段:

    app/models/item.rb

    class Item < ActiveRecord::Base
      belongs_to :seller, :class_name => "Vendor"
      belongs_to :manufacturer, :class_name => "Vendor"
    end
    

    app/models/vendor.rb

    class Vendor < ActiveRecord::Base
      has_many :sold_items, :class_name => "Item", :foreign_key => :seller_id
      has_many :manufactured_items, :class_name => "Item", :foreign_key => :manufacturer_id
    end
    

    spec/factories.rb

    require 'populator'
    require 'faker'
    
    FactoryGirl.define do
    
      factory :vendor do |v|
        v.name            {Populator.words(1..3)}
        v.website         {Faker::Internet.domain_name}
        v.abbr            {(["ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU", "VWX", "YZ1"])[rand(9)]}
      end
    
      factory :item do |i|
        i.association :seller, :factory => :vendor
        i.association :manufacturer, :factory => :vendor
        i.name  {Populator.words(3..5)}
      end
    
    end
    

    lib/tasks/populator.rake

    namespace :db do  
      desc "Erase database"
      task :erase => :environment do
        puts "Erasing..."
    
        [Vendor, Item].each(&:delete_all)
      end
    
      desc "Erase and fill database"
      task :populate => [:environment, :erase] do
        require 'populator'
        require 'faker'
    
        puts "Populating: enjoy this random pattern generator while you wait..."
    
        50.times{Factory.create(:vendor)}
        Vendor.all.each do |v|
          # This line actually has a bug in it that makes all `seller_id` and `manufacturer_id`
          # columns always contain a value in the range 0..50. That means
          # `rake db:populate` will only actually work the first time, but
          # I think you get the idea of how this should work.
          10.times{Factory.create(:item, :seller_id => (rand(50) + 1), :manufacturer_id => (rand(50) + 1))}
          print (['\\', '/', '_', '|'])[rand(4)]
        end
    
        puts ""
      end
    end
    

    【讨论】:

    • 感谢您的意见,但不幸的是,这并没有解决我的问题。告诉我谷歌的答案也无济于事。你看到我上面描述的细节了吗? item.manufacturer 返回一个供应商对象,但它无法响应名称等供应商方法。
    • 我正在打电话回答这个问题,希望能给您指明正确的方向。明天我会仔细研究一下并完善我的答案。别担心 - 我还没有完成。
    • 嗯,我正在解决一个错误,我不能像 vendor.sold_items 这样调用 - 我会尽快更新代码。
    • 修复了错误,使用最新的控制台测试更新了 README 文件,并确认关联在两个方向上都有效。推送到我在答案中引用的 GitHub 存储库的更改。
    • 非常感谢!!!!!!!这是非常有用和详细的,代码很棒。我可以确认它对我有用。你太棒了,谢谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2012-05-15
    • 1970-01-01
    相关资源
    最近更新 更多