代码之家  ›  专栏  ›  技术社区  ›  VP.

在Rails活动记录中可访问的属性

  •  10
  • VP.  · 技术社区  · 16 年前

    当我使用 attr_accessible 要指定我将公开模型中的哪些字段,脚本/控制台也是这样吗?我指的是一些我没有具体说明的东西 可访问的 也不能通过控制台访问吗?

    5 回复  |  直到 14 年前
        1
  •  19
  •   Josh Delsman    16 年前

    这只适用于批量分配。例如,如果要设置 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
  •  7
  •   Simone Carletti    16 年前

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

        3
  •  7
  •   maya    14 年前

    我找到了原因:

    指定可以通过质量分配设置的模型属性的白名单,例如 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
  •  1
  •   maya    14 年前

    当你指定一些事情 attr_accessible 只有这些东西可以在控制台或通过网站界面访问。

    假设你 name email 成为 可访问的 以下内容:

    attr_accessible :name, :email
    

    被遗弃 created_at updated_at (你应该这样做)。 然后您只能在控制台中编辑/更新这些字段。

        5
  •  0
  •   magicgregz    14 年前

    如果要从模型中公开字段,可以使用

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

    或者,如果要向属性中添加一些行为,则必须使用虚拟属性。

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

    干杯。