1

我的Product模型具有属性private。我想制作一种方法,允许当前用户能够选择他们的私人产品和其他产品 private = false

class Product < ActiveRecord::Base
  attr_accessible :name, :private
  belongs_to :user

  def permission
    unless self.current_user
      unless self.private
      end
    end
  end
end

开始是这样的吗?我将如何编写此方法?目标是将其放在选择菜单中。

4

1 回答 1

2

我会为此创建一个类方法,你会传递类似current_user的东西

class Product < ActiveRecord::Base
  attr_accessible :name, :private
  belongs_to :user

  def self.for_user_or_public(user)
    where("user_id = ? or private = ?", user.id, false)
  end
end

用法:

products = Product.for_user_or_public(current_user)

至于选择,应该像下面这样

<%= f.collection_select :owner_id, Product.for_user_or_public(current_user), :user_id, :name, { :include_blank => true } %>
于 2012-08-25T19:46:39.357 回答