相同模型之间的两个has_many链接 [英] Two has_many links between the same models

查看:77
本文介绍了相同模型之间的两个has_many链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有个用户,这些用户通过habtm链接拥有了产品,并且有效.

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)

但是,当我在我的用户产品模型中编写一个新链接时,该应用程序就搞砸了,因为我无法区分 creator (很多)产品的所有者提供的产品.

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

数据库正常,我可以将user_id存储在产品的创建者"列下,但是链接 product.creator.name 不起作用(因为该模型不正确,我以为),我只能读取列中的user_id,而无法获取具有其所有属性的用户对象.

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 可以完美地工作,但是只有当我删除了创建者的新链接时……

rem : user.products works perfectly, but only when I remove my new link for creator...

谢谢!

推荐答案

:as语法适用于多态关联-这不是您想要的.您对列名的评论有点含糊,因此我假设您在products表中有一个user_id列,该列是该产品的创建者的ID(我只包括相关的协会)...

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

这篇关于相同模型之间的两个has_many链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆