2013-01-16 36 views
1

鑑於這種has_many, :through場景:獲得兄妹記錄到的has_many,:通過關係

article.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 

brand.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 

user.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 

回答

1

的解決方案是不快簡單:

@articles = current_user.brand.articles 

運氣好的話,可以幫助別人。