切换非 attr_accessible 变量
我正在创建一个 Rails 应用程序,它是一个博客平台,有许多撰稿人。我的 User 模型有一个 :writer 布尔属性来指示特定用户是否有权发布文章。为了防止批量分配,:writer 属性未列在 user 模型的 attr_accessible 下。相反,我考虑创建一个类似于以下内容的函数,以允许切换编写者权限:
def toggle_writer
if User.find(:id).writer?
User.find(:id).update_attribute(:writer, false)
else
User.find(:id).update_attribute(:writer, true)
end
flash[:success] = "User permissions toggled."
redirect_to admintools_users_path
end
不过,我对这种方法有几个问题:
- 我如何从视图中调用它?有没有办法通过 link_to 或 button_for 调用函数?
- 我应该把这样的功能放在哪里?在控制器中,还是助手中?
- 我需要编辑 config/routes.rb 文件中的任何路由吗?
预先感谢您的帮助!
I am creating a Rails application that is a blogging platform, with many contributing writers. My User model has a :writer boolean attribute to indicate whether or not a particular user has permission to publish an article. In order to prevent mass assignment, the :writer attribute is NOT listed under attr_accessible for the User model. Instead, I thought of creating a function similar to the following, to allow for toggling of the writer-permissions:
def toggle_writer
if User.find(:id).writer?
User.find(:id).update_attribute(:writer, false)
else
User.find(:id).update_attribute(:writer, true)
end
flash[:success] = "User permissions toggled."
redirect_to admintools_users_path
end
I have several questions regarding this approach, though:
- How would I invoke this from a view? Is there a way to invoke a function via a link_to or button_for?
- Where would I put such a function? In a controller, or helper?
- Would I need to edit any routes in the config/routes.rb file?
Thanks in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
users_controller
中,效果会更好。是的,你会的。由于此操作将更新单个用户,因此您应该在
routes.rb
中执行以下操作:现在您可以将此路由与
link_to
一起使用,例如link_to("Toggle writer",toggle_writer_for_user_path(@user))
,其中@user
是您可以从params[:id]
获取。users_controller
.Yes, you would. As this action is going to update a single user, so, you should do the following in
routes.rb
:Now you can use this route with
link_to
, likelink_to("Toggle writer", toggle_writer_for_user_path(@user))
, where@user
is you can get fromparams[:id]
.