【发布时间】:2014-12-17 20:01:18
【问题描述】:
所以在我的 wiki 模型中,我有一个私有属性。如果 private 为真,那么未通过 HABTM 关系分配给 wiki_id 的用户不应查看该 wiki。
wiki.rb:
class Wiki
include Mongoid::Document
include Mongoid::Timestamps
has_and_belongs_to_many :users
field :title, type: String
field :body, type: String
field :private, type: Boolean, default: false
scope :visible_to, ->(user) {
user.present? || user.blank? ?
where(:private => false) : where(:private => false).or(:id => user.wiki_ids)
}
def public?
!self.private?
end
end
维基控制器:
def index
#@wikis = policy_scope(Wiki)
#@wikis = Wiki.all
@wikis = Wiki.visible_to(current_user)
authorize @wikis
end
def show
@wiki = Wiki.find(params[:id])
end
def new
@wiki = Wiki.new
authorize @wiki
end
def create
@wiki = current_user.wikis.build(params.require(:wiki).permit(:title, :body, :private, :user))
authorize @wiki
if @wiki.save
flash[:notice] = "Wiki was saved."
redirect_to @wiki
# report success
else
flash[:error] = "There was an error saving your wiki. Please try again."
render :new
end
我非常有信心它需要在模型中修改的范围,因为如果我注释掉模型中的范围并将控制器中的索引替换为 Wiki.all。我看到所有的维基。 截至目前,作为创建 wiki 并将其标记为私有并且我已登录的人,我没有看到该 wiki,也没有任何人作为用户添加到 wiki。
我尝试在末尾添加其他条件,例如 user.present? ? where(:id => user.wiki_ids) 和 user.present? && where(:id => user.wiki_ids),但只是将错误返回给我。
用户的数据库条目:
User_id: 547eb8867261691268000000, wiki_ids: [BSON::ObjectId('54807226726 1690be0260000'),
BSON::ObjectId('5480735c7261690bae000000'), BSON::ObjectId('548
136e57261690aef000000'), BSON::ObjectId('5489af337261690d95000000'),
BSON::Objec tId('5489b57e7261690d95010000'),
BSON::ObjectId('548f9f607261690bb5060000'), BSO
N::ObjectId('54908f127261690be8000000'),
BSON::ObjectId('54908f207261690be801000 0')], name: "Carey VonRueden",
email: "admin@email.com", encrypted_password: "$2a
$10$NrlQ2XH64UucOPcI1aje9.57eoSO74676264YrIjfGvncyGcpGWy",
reset_password_token : nil, reset_password_sent_at: nil,
remember_created_at: nil, sign_in_count: 7, current_sign_in_at:
2014-12-17 18:51:15 UTC, last_sign_in_at: 2014-12-16 02:38:5 8 UTC,
current_sign_in_ip: "10.0.2.2", last_sign_in_ip: "10.0.2.2",
confirmation
_token: nil, confirmed_at: 2014-12-03 07:15:18 UTC, confirmation_sent_at: nil, u nconfirmed_email: nil, role: "admin">
Wiki 的数据库条目:
Wiki _id: 54908f207261690be8010000, created_at: 2014-12-16 19:59:28 UTC, updated_at: 2014-12-16 19:59:28 UTC, user_ids:
[BSON::ObjectId('547eb886726169126 8000000')], title: "Private", body:
"Private", private: true>
【问题讨论】:
-
Answer: 所以我得到了下面的为我工作。 wikiscontroller def index @wikis = policy_scope(Wiki) end
标签: ruby-on-rails ruby scope policy