Rails ActiveRecord- has_many through and belongs_to a related model
Posted
by Nick
on Stack Overflow
See other posts from Stack Overflow
or by Nick
Published on 2010-03-22T23:29:21Z
Indexed on
2010/03/22
23:31 UTC
Read the original article
Hit count: 258
I have 3 models
sites, user_favorites and users. Relevant relationships:
class Site < ActiveRecord::Base
has_many :users, :through => :user_favorites
class UserFavorite < ActiveRecord::Base
belongs_to :user, :counter_cache => true
belongs_to :site
end
class User < ActiveRecord:Base
has_many :user_favorites
has_many :sites, :through => :user_favorites
All of that works just fine. I'd like to add a new attribute to the Site model to indicate which user created it.
I don't believe this constitutes a has_and_belongs_to_many scenario. A site has many users through user_favorites but I want it to belong to a single user reflecting the owner/creator.
I'm wondering what the ORM best practice is for this. SQL wise I'd just use different joins depending on what I was trying to query with a created_by FK in Site. Sorry if I'm missing something basic here.
Thanks
© Stack Overflow or respective owner