Rails - 显示/管理多对多关系

时间:2014-10-15 15:48:39

标签: ruby-on-rails many-to-many relationship

我是精彩Rails世界的初学者,但我发现了一些困难。

这是我的情况:

我有一些用户,使用Webapps的用户,并且出现了一个连接表," Quota",用于跟踪每个webapp上每个用户的活动。

因此,在Quota的数据库表中我们找到:user_id,webapp_id,quantity:int。

我的模特:

class Webapp < ActiveRecord::Base
  #has_many :webapps_quota, :through => :quota, source: :user
  has_and_belongs_to_many :quota
  accepts_nested_attributes_for :quota
end

class Webapp < ActiveRecord::Base
  #has_many :webapps_quota, :through => :quota, source: :webapp 
  has_and_belongs_to_many :quota
  accepts_nested_attributes_for :quota
end

class Quota < ActiveRecord::Base
 belongs_to :user
 belongs_to :webapp
 accepts_nested_attributes_for :user
 accepts_nested_attributes_for :webapp
end

我非常渴望如何解决这个问题。例如,如何向用户显示配额?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

要在关联表中添加属性,您应该使用has_many through关联:

class User < ActiveRecord::Base
  has_many :quotas
  has_many :webapps, through: :quotas
end

class Quota < ActiveRecord::Base
  belongs_to :user
  belongs_to :webapp
end

class Webapp < ActiveRecord::Base
  has_many :quotas
  has_many :users, through: :quotas
end

您的问题:How do I show his quota to an user for example?

user = User.find(1)
user.quotas  #display the quotas for that user
user.webapps #display the webapps for that user
相关问题