切换非 attr_accessible 变量

发布于 2024-11-07 20:25:32 字数 787 浏览 2 评论 0原文

我正在创建一个 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

不过,我对这种方法有几个问题:

  1. 我如何从视图中调用它?有没有办法通过 link_tobutton_for 调用函数?
  2. 我应该把这样的功能放在哪里?在控制器中,还是助手中?
  3. 我需要编辑 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:

  1. How would I invoke this from a view? Is there a way to invoke a function via a link_to or button_for?
  2. Where would I put such a function? In a controller, or helper?
  3. Would I need to edit any routes in the config/routes.rb file?

Thanks in advance for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌伤ぢ 2024-11-14 20:25:32
  1. 是的,你可以。
  2. 如果将其放入 users_controller 中,效果会更好。
  3. 是的,你会的。由于此操作将更新单个用户,因此您应该在 routes.rb 中执行以下操作:

     资源:用户做的
       member do #this 表示您正在对某个对象执行操作
         获取:toggle_writer,:as => :toggle_writer_for # 此行将生成toggle_writer_for_user_path 路由
       结尾
     结尾
    

现在您可以将此路由与 link_to 一起使用,例如 link_to("Toggle writer",toggle_writer_for_user_path(@user)),其中@user是您可以从params[:id]获取。

  1. Yes you can.
  2. Better if you put it in the users_controller.
  3. Yes, you would. As this action is going to update a single user, so, you should do the following in routes.rb:

     resources :users do
       member do #this means you are doing with a certain object
         get :toggle_writer, :as => :toggle_writer_for # this line will generate toggle_writer_for_user_path route
       end
     end
    

Now you can use this route with link_to, like link_to("Toggle writer", toggle_writer_for_user_path(@user)), where @user is you can get from params[:id].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文