我为发布文章的用户创建了下表:
create_table "article", force: true do |t|
t.boolean "approved", default: false
t.string "content",
t.integer "category_id",
t.string "title"
end
现在我想限制对一列的访问。普通用户可以编辑他们的文章字段(content, category_id, title
),但无法编辑列approved
。列approved
只能由管理员编辑。
我跟着Michael Hartl's tutorial,我已经完成了用户的授权。我有一个帮助器,我有一个方法,我可以轻松检查当前登录用户管理员logged_in_user.admin
,这给了我真或假。
如何保护表格以防止有意图的常规用户更改approved
列?
答案 0 :(得分:0)
假设您article_params
中有ArticlesController
方法。修改如下:
def article_params
if logged_in_user.admin
params.require(:article).permit(:approved, :content, :category_id, :title)
else
params.require(:article).permit(:content, :category_id, :title)
end
end
如果logged_in_user
仅为admin
,则允许approved
属性保存在数据库中。
确保在创建/更新文章时使用article_params
方法允许参数。