【问题标题】:Restrict attr_accessible to types of user with Ruby on Rails使用 Ruby on Rails 将 attr_accessible 限制为用户类型
【发布时间】:2012-07-02 02:53:57
【问题描述】:

我正在创建一个论坛软件。我希望管理员和模组能够关闭某些主题。

对代码进行清理以仅显示相关信息。

模型

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation, :bio
  has_many :topics, dependent: :destroy
end

class Topic < ActiveRecord::Base
  belongs_to :user
  attr_accessible :name, :last_post_id, :content
end

用户架构:admin 和 mod 列确定管理员和 mod。

create_table "users", :force => true do |t|
  t.string   "name"
  t.string   "email"
  t.datetime "created_at",                         :null => false
  t.datetime "updated_at",                         :null => false
  t.string   "password_digest"
  t.string   "remember_token"
  t.boolean  "admin",           :default => false
  t.text     "bio"
  t.boolean  "mod",             :default => false
end

主题架构:关闭列决定主题的关闭状态。

create_table "topics", :force => true do |t|
  t.datetime "created_at",                      :null => false
  t.datetime "updated_at",                      :null => false
  t.integer  "forum_id"
  t.string   "name"
  t.integer  "last_post_id"
  t.integer  "views"
  t.integer  "user_id"
  t.boolean  "closed",       :default => false
  t.text     "content"
end

我不愿意用户 attr_accessible :closed 使用 TOPIC 模型,因为它容易受到恶意 PUT 请求的攻击(如果我错了,请纠正我)。

Rails 应用有什么方法可以在不使用attr_accessible 的情况下访问和修改TOPIC 的closed 列的值,这样只有模组和管理员才能编辑它们?

【问题讨论】:

    标签: ruby-on-rails attr attr-accessible


    【解决方案1】:

    我在谷歌上搜索并找到了这个ascii cast

    基本上,您正在寻找动态 attr_accessible。

    如果你目前有

    class Article < ActiveRecord::Base  
      attr_accessible :name, :content, :closed  
    end  
    

    你可以像这样使用动态 attr_accessible :

    class Article < ActiveRecord::Base  
      attr_accessible :name, :content  
      private  
      def mass_assignment_authorizer  
        super + [:closed]  
      end  
    end  
    

    我希望我是你正在寻找的。 请务必查看我给您的链接以获取完整参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 2013-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多