I've got two models, Item and Product as follows:
irb(main):007:0> Item
=> Item(id: integer, identification_number: string, production_date: date,
created_at: datetime, updated_at: datetime, going_in: boolean)
irb(main):008:0> Product
=> Product(id: integer, sku: string, barcode_identification: string,
created_at: datetime, updated_at: datetime)
Think of this as an item is of a particular product.
I've managed to refer all the items of a particular product (Product.find(1).items) via
class Product < ActiveRecord::Base
has_many :items, :foreign_key => "identification_number",
:primary_key => "barcode_identification"
end
but I can't seem to refer the Product of a particular item. This is what I've got now:
class Item < ActiveRecord::Base
set_primary_key :identification_number
belongs_to :product, :foreign_key => "barcode_identification"
end
And as far as my understanding re: databases are concerned, that should work. Except that it doesn't. Maybe I'm missing out on something here? I'm fairly new to rails (around a month or less.)
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
A has_many association is similar to has_one , but indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model.
Does it have to be a belongs_to
? Since you're specifying both primary and foreign key, why not
class Product < ActiveRecord::Base
has_many :items, :foreign_key => "identification_number",
:primary_key => "barcode_identification"
end
class Item < ActiveRecord::Base
has_one :product, :foreign_key => "barcode_identification",
:primary_key => "identification_number"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With