Two has_many links between the same models

守給你的承諾、 提交于 2019-12-01 11:49:02

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!