简体   繁体   English

在Ruby on Rails中访问虚拟属性的正确方法是什么?

[英]What is the proper way to access virtual atributes in Ruby on Rails?

I have a model w/ a virtual attribute: 我有一个具有虚拟属性的模型:

class Campaign < ActiveRecord::Base  
  def status
     if deactivated
       return "paused"
     else
       return "live"
     end
  end
end

now, in my view, when I access the attribute with campaign.status , I am getting the proper result. 现在,在我看来,当我使用campaign.status访问该属性时,我得到了正确的结果。 However, when I try to access it like this campaign[:status] , I get nothing back. 但是,当我尝试像这个campaign[:status]那样访问它时,我什么也得不回来。

Why is that? 这是为什么?

[:status] uses the [] method in Ruby. [:status]使用Ruby中的[]方法。 'def status' defines a method which shouldn't be mistaken with an ActiveRecord attribute or an virtual attribute (eg attr_reader or attr_accessor). 'def status'定义了一个不应该与ActiveRecord属性或虚拟属性(例如attr_reader或attr_accessor)混淆的方法。 ActiveRecord adds the [] method to your class and makes all the (database) attributes accessible by object[:attr_name] AND object.attr_name(And even object.attributes[:attr_name]). ActiveRecord将[]方法添加到您的类中,并使对象[:attr_name] AND object.attr_name(甚至object.attributes [:attr_name])可以访问所有(数据库)属性。

This is different from how fe Javascript works where obj[:method] is virtually the same as obj.method. 这与fe javascript的工作方式不同,其中obj [:method]与obj.method几乎相同。

Edit: You should be able to use the attr_accessor if you use them for example in any form: 编辑:如果你以任何形式使用它们,你应该可以使用attr_accessor:

<%= form.input :status %>

Submitting the form will then set the instance variable @status. 然后,提交表单将设置实例变量@status。 If you want to do anything with this before or after saving you can call an before_save or after_save hook: 如果你想在保存之前或之后对此做任何事情,你可以调用before_save或after_save钩子:

class Campaign < ActiveRecord::Base  
  attr_accessible :status
  attr_accessor :status
  before_save :raise_status

  def raise_status
    raise @status
  end
end

This will throw an error with the value submitted value for status. 这将为状态的值提交值引发错误。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM