开发者

How do I associate my objects so that a many-to-many relation can be used as one-to-many in Rails?

开发者 https://www.devze.com 2023-04-02 09:28 出处:网络
Please excuse the confusing phrasing in the title. In my RoR project let\'s say I have it set up like this

Please excuse the confusing phrasing in the title. In my RoR project let's say I have it set up like this

class Product < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

and

class Category < ActiveRecord::Base
  has_and_belongs_to_many :products
end

I then have a categories_products table that connects them. This works fine but my problem is that a product will only ever have one category at a time and I'd of course like to do 开发者_高级运维product.category instead of having to deal with an array. How can I accomplish that?


A one-to-many representation is demonstrated in the rails guides like this:

class Category < ActiveRecord::Base
  has_many :products
end

class Product < ActiveRecord::Base
  belongs_to :category
end
0

精彩评论

暂无评论...
验证码 换一张
取 消