通过has_many,:通过关系获取兄弟姐妹记录

时间:2013-01-16 01:16:37

标签: ruby-on-rails-3 has-many-through

鉴于此has_many, :through方案:

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的{​​{1}}条记录?这些方面的东西:

Brand

修改

这样的事情应该有效,对吧?我只是无法弄清楚语法。

class Article < ActiveRecord::Base
  scope :branded_articles, lambda { |user| where('brand_ids = ?', user.brand) }
end

1 个答案:

答案 0 :(得分:1)

解决方案非常简单:

@articles = current_user.brand.articles

运气好,帮助别人。