custom attr_reader in rails - ruby-on-rails

Mostly in rails if you write my_obj.attr it looks up attr in the database and reports it back. How do you create a custom def attr method that internally queries the database for attr, modifies it and returns? In other words, what's the missing piece here:
# Within a model. Basic attr_reader method, will later modify the body.
def attr
get_from_database :attr # <-- how do I get the value of attr from the db?
end

Something like that:
def attr
value = read_attribute :attr
value = modify(value)
write_attribute :attr, value
save
value
end

Neutrino's method is good if you want to save a modified value back to the database each time you get the attribute. This not recommended since it will execute an extra database query every time you try to read the attribute even if it has not changed.
If you simply want to modify the attribute (such as capitalizing it for example) you can just do the following:
def attr
return read_attribute(:attr).capitalize #(or whatever method you wish to apply to the value)
end

Related

How to assign Rails model column by symbol

I have a method like this:
class Foo < ActiveRecord::Base
def load_data(data)
self.foo = data[:foo] if data.has_key?(:foo)
self.bar = data[:bar] if data.has_key?(:bar)
self.moo = data[:moo] if data.has_key?(:moo)
self.save
end
end
I want to write the method like this:
[:foo, :bar, :moo].each do |sym|
# need some trick here
self.sym = data[sym] if data.has_key?(sym)
end
Of course this method doesn't work, how can I assign a value to a Model column by using a symbol?
vee's answer is correct for the general case, but since this is Rails and ActiveRecord, you can take some nice shortcuts:
def load_data(data)
update_attributes data.slice(:foo, :bar:, :moo)
end
This works because data.slice filters your data hash to just the given keys, and then update_attributes will set those values in your model and invoke #save. When the keys aren't present, they aren't written, so you don't need to check and assign each key separately.
If you don't care about filtering the inbound data and simply assigning the keys given to the model, then just update_attributes data and you're done.
You can use send:
[:foo, :bar, :moo].each do |sym|
# need some trick here
send "#{sym}=", data[sym] if data.has_key?(sym)
end

Attributes as local variables vs instance variables in Rails Validations

In custom validation methods, why are the attributes passed as local variables instead of being accessible as instance variables?
I was expecting to use #title instead of title in the custom validation below, but #title is nil in the code below. title contains the actual data.
attr_accessible :title
validate :do_check_title
def do_check_title
title =~ /^Alice in/ || errors.add(:title, "Not Alice in Wonderland")
end
Looking through the active_record/core.rb
def initialize(attributes = nil)
...
assign_attributes(attributes) if attributes
...
end
And then in active_record/attribute_assignment.rb
def _assign_attribute(k, v)
public_send("#{k}=", v)
So I guess, the attributes should be available as instance variables in the validation function.
Why are they nil?
It doesn't really matter if you access these from a validation or other instance methods. You can see what's happening from the console (pry):
u = User.first
show-method u.first_name=
This gives you something like this:
generated_attribute_methods.module_eval("def #{attr_name}=(new_value); write_attribute('#{attr_name}', new_value); end", __FILE__, __LINE__)
Now if you take a look at the write_attribute method, you can see that it deletes attribute cache etc. and then assign to attributes and it's just a hash.
u.attributes
So from now on, instead of the boring u.first_name = "foo", you can use this:
u.send :write_attribute, "first_name", "foo"
and it will do the same thing (3.2.10).
ActiveRecord stores the values in the attributes hash and not in instance variables. I generates accessor (getter/setter) methods on the fly while you access them.
Rails needs to support the livecycle of an entity, and wraps this code in the generated methods. This is needed, so that it can support ie. dirty? and changed? methods.
The next thing are associations, they are handled through proxies, so you need to call them with methods too.
Instance variables could be seen as volatile data. They are transparent to the persistance layer.

Rails override attribute using his getter

I have a price attribute in my model.
Can I use attribute-getter, which is named just like the attribute
def price
... logic logic ..
return something
end
in order to override the attribute itself ?
Currently it doesn't work. If I call model.price it works, but when it somes to saving the object via model.save, it stores the default value.
Can it be done in a painless way, or should I make a before_save callback?
If you set a value in Ruby you access the setter method. If you want to override the setter you have to do something like this:
def price=(_price)
# do some logic
write_attribute(:price, _price)
end
This is of course a discussion point. Sometimes you can better use a callback. Something like this:
before_save :format_price
private
def format_price
# Do some logic, for example make it cents.
self.price = price * 100
end
Since you seem to want the "real" value stored in the database, what you probably want to do is modify the setter. This way the actual value is stored, and the price getter can just return it unmodified.
You can do this via the lower level write_attribute method. Something like:
def price=(value)
# logic logic
self.write_attribute(:price, value)
end
If you want to manipulate the attribute's value right before it's saved then using a callback would be a better way, since this is what callbacks are for.

Order of params stops *_attributes= from working

So I've implemented a hack and I want to know what the "proper" way is to do it.
The issue is that I have an *_attributes=() method that uses an instance variable. The reason this is a problem is that at the time the method is called, that instance variable hasn't been set. Here is the method in question:
def proposed_times_attributes=(attributes)
attributes.each do |key,value|
value[:timezone] = timezone
end
assign_nested_attributes_for_collection_association(:proposed_times, attributes)
end
The timezone is in the params hash after proposed_times_attributes. Therefore my hack is to delete it from params, then add it back, thus moving it to the end of the line.
def create
p = params[:consultation]
a = p.delete(:proposed_times_attributes)
p[:proposed_times_attributes] = a
#consultation = current_user.advised_consultations.new(p)
...
end
What is the proper way that I should be doing this?
new() calls load() where the loop is that goes through each key/value pair.
Thankfully I'm using Ruby 1.9.2 which keeps the order, but it would be nice to know how to do this so that it wouldn't depend on this fact.
If the next operation after new will always be a save operation, you can store the attributes in an accessor, and use a before_validation callback to operate on them as you wish.
class Consultations < ActiveRecord::Base
attr_accessor :proposed_times_attributes
before_validation :assign_proposed_times
def assign_proposed_times
proposed_times_attributes.each do |key,value|
value[:timezone] = timezone
end
assign_nested_attributes_for_collection_association(:proposed_times, attributes)
end
end
Now in your controller you simply have:
def create
#consultation = current_user.advised_consultations.new(params[:consultation])
...
end
If you wish to do other operations before calling save, then pulling out the param as you did in your example, then passing it to an appropriate method after calling new would be the way to go.

Rails: Initializing attributes that are dependent on one another

I have the following classes in my ActiveRecord model:
def Property < ActiveRecord::Base
# attribute: value_type (can hold values like :integer, :string)
end
def PropertyValue < ActiveRecord::Base
belongs_to property
# attribute: string_value
# attribute: integer_value
end
A PropertyValue object is intended to hold only a string value or an integer value, depending on the type, specified in the value_type attribute of the associated Property object. Obviously, we shouldn't bother the user of the PropertyValue class with this underlying string_value/integer_value mechanism. So I'd like to use a virtual attribute "value" on PropertyValue, that does something like this:
def value
unless property.nil? || property.value_type.nil?
read_attribute((property.value_type.to_s + "_value").to_sym)
end
end
def value=(v)
unless property.nil? || property.value_type.nil?
write_attribute((property.value_type.to_s + "_value").to_sym, v)
end
end
I want to offer the user a view to fill in a bunch of property values, and when the view is posted, I'd like to have PropertyValue objects instantiated based on the list of attributes that is passed in from the view. I'm used to using the build(attributes) operation for this. However, the problem now occurs that I don't have any control over the order in which the attribute initialization takes place. Thus the assignment of the value attribute will not work when the association with the Property attribute has not yet been made, since the value_type cannot be determined. What is the correct "Rails" way to deal with this?
BTW, as a workaround I have tried the following:
def value=(v)
if property.nil? || property.value_type.nil?
#temp_value = v
else
write_attribute((property.value_type.to_s + "_value").to_sym, v)
end
end
def after_initialize
value = #temp_value
end
Apart from the fact that I think this is quite an ugly solution, it doesn't actually work with the "build" operation. The #temp_value gets set in the "value=(v)" operation. Also, the "after_initialize" in executed. But, the "value = #temp_value" does not call the "value=(v)" operation strangely enough! So I'm really stuck.
EDIT: build code
I indeed realized that the code to build the Property objects would be handy. I'm doing that from a Product class, that has a has_many association with Property. The code then looks like this:
def property_value_attributes=(property_value_attributes)
property_value_attributes.each do |attributes|
product_property_values.build(attributes)
end
end
At the same time I figured out what I did wrong in the after_initialize operation; it should read:
def after_initialize
#value = #temp_value
end
The other problem is that the property association on the newly built property_value object will never be set until the actual save() takes place, which is after the "after_initialize". I got this to work by adding the value_type of the respective property object to the view and then having it passed in through the attributes set upon post. That way I don't have to instantiate a Property object just to fetch the value_type. Drawback: I need a redundant "value_type" accessor on the PropertyValue class.
So it works, but I'm still very interested in if there's a cleaner way to do this. One other way is to make sure the property object is attached first to the new PropertyValue before initializing it with the other attributes, but then the mechanism is leaked into the "client object", which not too clean either.
I would expect some sort of way to override the initializer functionality in such a way that I could affect the order in which attributes get assigned. Something very common in languages like C# or Java. But in Rails...?
One option is to save the Property objects first, and then add the PropertyValue objects afterwards. If you need to you could wrap the whole thing in a transaction to ensure that the Properties are rolled back if their corresponding PropertyValues could not be saved.
I don't know what your collected data from the form looks like, but assuming it looks like the following:
#to_create = { :integer => 3, :string => "hello", :string => "world" }
You could do something like this:
Property.transaction do
#to_create.keys.each do |key|
p = Properties.create( :value_type => key.to_s )
p.save
pval = p.property_value.build( :value => #to_create[key] )
pval.save
end
end
That way you don't have to worry about the nil check for Property or Property.value_type.
As a side note, are you sure you need to be doing all this in the first place? Most database designs I've seen that have this kind of really generic meta-information end up being highly non-scalable and are almost always the wrong solution to the problem. It will require a lot of joins to get a relatively simple set of information.
Suppose you have a parent class Foo that holds the property/value pairs. If Foo has ten properties, that requires 20 joins. That's a lot of DB overhead.
Unless you actually need to run SQL queries against PropertyValues (e.g. "get all Foos that have the property "bar"), you could probably simplify this a lot by just adding an attribute called "properties" to Foo, then serializing your Properties hash and putting it in that field. This will simplify your code, your database design, and speed up your application as well.
Oh jeeezzzz... this is insanely simple, now that I puzzled on it a little more. I just need to override the "initialize(attributes = {})" method on the PropertyValue class like so:
def initialize(attributes = {})
property = Property.find(attributes[:property_id]) unless attributes[:property_id].blank?
super(attributes)
end
Now I'm always sure that the property association is filled before the other attributes are set. I just didn't realize soon enough that Rails' "build(attributes = {})" and "create(attributes = {})" operations eventually boil down to "new(attributes = {})".
Probably you should try to use ActiveRecord get/set methods, i.e.:
def value
send("#{property.value_type}_value") unless property || property.value_type
end
def value=(v)
send("#{property.value_type}_value=", value) unless property || property.value_type
end

Resources