简体   繁体   中英

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. However, when I try to access it like this campaign[:status] , I get nothing back.

Why is that?

[:status] uses the [] method in 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). 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]).

This is different from how fe Javascript works where obj[:method] is virtually the same as obj.method.

Edit: You should be able to use the attr_accessor if you use them for example in any form:

<%= form.input :status %>

Submitting the form will then set the instance variable @status. If you want to do anything with this before or after saving you can call an before_save or after_save hook:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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