鉴于这种has_many, :through
情况:
文章.rb
class Article < ActiveRecord::Base
attr_accessible :body, :issue, :name, :id, :brand_ids
has_many :publications
has_many :docs, :through => :publications
has_many :silos
has_many :brands, :through => :silos
end
品牌.rb
class Brand < ActiveRecord::Base
attr_accessible :name, :logo1, :logo2, :colour1, :colour2
has_many :users
has_many :prices, :dependent => :destroy
has_many :silos
has_many :articles, :through => :silos
end
用户.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
attr_accessor :current_password
attr_accessible :name, :password, :password_confirmation, :current_password, :email, :remember_me, :brand_id
belongs_to :brand
end
我将如何编写范围、方法或助手来获取与当前用户Article
共享的记录?Brand
这些方面的东西:
class Article < ActiveRecord::Base
scope :branded_articles, lambda { |user| where('brand_ids = ?', user.brand) }
end
编辑
这样的事情应该有效,对吧?我只是无法弄清楚语法。
Article.all.brands.find(1) #should find all articles available to a brand with an ID of 1