所以在我的wiki模型中,我有一个私有属性。如果private为true,则不应通过HABTM关系向未分配给wiki_ids的用户查看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
WikisController:
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,也没有任何人将我作为用户添加到维基。
我尝试在最后添加其他条件,例如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>
答案 0 :(得分:0)
您的范围条件错误
user.present? || user.blank?
- >总是如此。如果用户在场或用户为空,则它将始终只返回公共维基
将您的范围更改为以下内容。(假设您希望所有公共维基用户都未登录。如果用户已登录,则需要公开+用户创建的维基)
scope :visible_to, ->(user) {
user.nil? ? where(:private => false) : where(:private => false).or(:id => user.wiki_ids)
}
如果您仍未达到预期效果,请检查user.wiki_ids
是否返回了正确的值