问题
I have users which have products through a habtm link, which is working.
I want to add a link between the user model and the product model, to keep track of the creator of that product (who doesn't always own the product, of course)
But when I write in my user and product models a new link, the application screws up because I can't distinguish the creator of a product from the owner of (a lot of) products.
Can you help me ? Here is my models :
class Product < ActiveRecord::Base
belongs_to :group
has_and_belongs_to_many :authors
has_and_belongs_to_many :users # THIS IS OK (with appart table)
has_many :users, :as => creator # THIS LINE DOES NOT WORK AT THE MOMENT
end
class User < ActiveRecord::Base
has_and_belongs_to_many :products
belongs_to :user # THIS LINE DOES NOT WORK AT THE MOMENT
default_scope :order => "username ASC"
end
The database is ok, and I can store the user_id under the creator column from my product, but the link product.creator.name doesn't work (because of the model is not correct, I presume), I can only read the user_id which is in the column but not get the user object with all his attributes.
rem : user.products works perfectly, but only when I remove my new link for creator...
Thanks !
回答1:
The :as
syntax is for polymorphic associations - this is not what you want. Your comments about your column names are a bit ambiguous, so I'm going to assume that you have a user_id
column in your products
table which is the id of the creator of that product (I'm only including the relevant associations)...
class Product < ActiveRecord::Base
has_and_belongs_to_many :users
belongs_to :creator, :foreign_key => :user_id, :class_name => "User"
end
class User < ActiveRecord::Base
has_and_belongs_to_many :products
has_many :owned_products, :class_name => "Product"
end
回答2:
There is a nice gem for that: https://github.com/spovich/userstamp
I used it in my project and it works good - you just adds 'stampable' to your models and then creator_id (and updater_id) are filled authomaticly.
来源:https://stackoverflow.com/questions/6509227/two-has-many-links-between-the-same-models