更新模型属性
我有一个 Rails 应用程序,它是一个博客平台,允许多个作者做出贡献。我的 User 模型有一个 :writer 布尔属性,用于分配写入权限。但是,:writer 未在 User 模型的 attr_accessible 下列出。
我想要一种通过网络编辑此属性的方法,而不必
User.find_by_id(user_id).update_attribute(:writer, true/false)
通过控制台运行,但我想知道如果不在 attr_accessible 下列出 :writer ,这是否不可能> 对于用户模型。我有几个页面只能由管理员用户访问,并且我希望能够在这些视图中切换 :writer 属性。
如果确实可以的话,又该如何做到呢?预先感谢您的帮助!
编辑:根据我得到的几个答案,我觉得我的问题应该更具体。我道歉。我知道我仍然可以单独更新 :writer 属性,正如 Beerlington 和 Hitesh 所指出的那样。我想知道的是如何通过视图来实现这样的功能。是否可以创建一个可点击的链接来切换 :writer 状态?是否可以让链接调用控制器函数并传递适当的 user_id 进行 :writer 切换?
I have a Rails app that is a blogging platform, allowing for multiple contributing authors. My User model has a :writer boolean attribute for assigning writing permissions. However, :writer is NOT listed under attr_accessible for the User model.
I wanted to a way to edit this attribute through the web, without having to run
User.find_by_id(user_id).update_attribute(:writer, true/false)
through the console, but I'm wondering if this would be impossible without listing :writer under attr_accessible for the User model. I have several pages accessible only to admin-users, and I would like to be able to put the ability to toggle the :writer attribute within those views.
If it is indeed possible, how could it be done? Thanks in advance for your help!
Edit: Based on the couple of answers I've gotten, I feel should've been more specific in my question. I apologize. I understand that I could still individually update the :writer attribute, as Beerlington and Hitesh have pointed out. What I wanted to know was how one could implement such a function through the view. Would it be possible to make a clickable link to toggle the :writer state? Might it be possible to have a link call a controller function and pass the appropriate user_id for :writer toggling?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
attr_accessible 和 attr_protected 仅保护来自批量分配的属性。不过,您仍然可以通过其他方式分配它们:
批量分配(不起作用):
非批量分配(选项 1):
非批量分配(选项 2):
非批量分配(选项 3):
我个人不喜欢其中任何一个手动选项,所以我编写了一个名为 sudo_attributes 的 gem,它可以更轻松地使用“sudo”方法覆盖批量分配。
attr_accessible and attr_protected only protect attributes from mass-assignment. You can still assign them through other means though:
Mass Assignment (will not work):
Non Mass Assignment (option 1):
Non Mass Assignment (option 2):
Non Mass Assignment (option 3):
I personally do not like either of these manual options, so I wrote a gem called sudo_attributes that makes it easier to override mass assignment using "sudo" methods.
用这个
use this