I have users其中有products通过 habtm 链接,该链接正在运行。
我想添加一个链接user模型和product模型,以跟踪creator该产品的(当然,谁并不总是拥有该产品)
但是当我写在我的user and product建立一个新的链接,应用程序搞砸了,因为我无法区分creator of a product来自(很多)的所有者products.
你能帮助我吗 ?这是我的模型:
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
数据库没问题,我可以将 user_id 存储在我的产品的创建者列下,但是链接产品.创建者.名称不起作用(我认为是因为模型不正确),我只能读取列中的 user_id,但无法获取具有所有属性的用户对象。
rem : 用户.产品工作完美,但只有当我删除创建者的新链接时......
Thanks !
The :as
语法用于多态关联 - 这不是您想要的。您对列名的评论有点含糊,所以我假设您有一个user_id
列在你的products
表是该产品的创建者的 id(我只包括相关关联)...
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)