在我的在线商店中,允许用户更改其订单的某些属性(例如,他们的账单地址),但不能更改其他属性(例如,原始 IP 地址)。另一方面,管理员可以修改所有订单属性。
鉴于此,我如何使用 :attr_accessible
来正确保护我的 Order 模型?或者我是否必须使用它来标记管理员可以修改的所有属性的可访问性,并避免在普通用户可以访问的那些 Controller 操作中使用 Order.update_attributes(params[:order])
?
最佳答案
一般来说,attr_accessible 不是您正在寻找的工具,而且 Rails 没有内置任何东西来满足您的需求。
如果你想细粒度地控制谁可以更新模型中的特定属性,你可以这样做:
class Order < ActiveRecord::Base
def update_attributes_as_user(values, user)
values.each do |attribute, value|
# Update the attribute if the user is allowed to
@order.send("#{attribute}=", value) if user.can_modify?(attribute)
end
save
end
end
然后您可以将 Order.update_attributes(params[:order])
更改为 Order.update_attributes_as_user(params[:order], current_user)
并假设您实现了User#can_modify?
方法在正确的情况下返回 true,它应该可以工作。
关于ruby-on-rails - 使用 :attr_accessible with role-based authorization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/791626/