【问题标题】:attr_accessible in rails Active Record轨道活动记录中的 attr_accessible
【发布时间】:2009-11-24 13:17:30
【问题描述】:

当我使用attr_accessible 指定我将公开模型中的哪些字段时,脚本/控制台也是如此吗?我的意思是我没有指定为 attr_accessible 的东西也不能通过控制台访问?

【问题讨论】:

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


    【解决方案1】:

    这仅适用于批量分配。例如,如果您要在模型中设置 attr_protected :protected

    >> Person.new(:protected => "test")
    => #<Person protected: nil>
    

    相反,您可以使用attr_accessible 将所有想要访问的属性设置为可访问。

    但是,以下方法仍然有效:

    >> person = Person.new
    => #<Person protected: nil>
    >> person.protected = "test"
    => #<Person protected: "test">
    

    这与控制器、视图等中的行为相同。attr_protected 仅防止大量分配变量,主要来自表单等。

    【讨论】:

      【解决方案2】:

      控制台的行为与 Rails 应用程序完全相同。如果您保护了特定模型的某些属性,您将无法从控制台或 Rails 应用程序本身批量分配这些属性。

      【讨论】:

        【解决方案3】:

        我找到了原因:

        指定可通过批量分配设置的模型属性白名单,例如new(attributes)update_attributes(attributes)attributes=(attributes)。 这与 attr_protected 宏相反:

         Mass-assignment will only set attributes in this list, to assign to the rest of 
        attributes you can use direct writer methods. This is meant to protect sensitive  
        attributes from being overwritten by malicious users tampering with URLs or forms. 
        If you‘d rather start from an all-open default and restrict attributes as needed,
        have a look at `attr_protected`.
        

        所以这意味着它只是避免批量分配,但我仍然可以设置一个值。

        【讨论】:

          【解决方案4】:

          当您将某些内容指定为attr_accessible 时,只有这些内容才能在控制台或网站界面中访问。

          例如:假设您将nameemail 设为attr_accessible

          attr_accessible :name, :email
          

          并省略了created_atupdated_at(你应该这样做)。 然后您只能在控制台中编辑/更新这些字段。

          【讨论】:

            【解决方案5】:

            如果你想在你的模型中公开一个字段,你可以使用

            attr_accessor :meth # for getter and setters
            attr_writer :meth # for setters
            attr_reader :meth # for getters
            

            或者如果你想为你的属性添加一些行为,你必须使用虚拟属性

            def meth=(args)
             ...
            end
            def meth
             ...
            end
            

            干杯。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多