Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy aren't Rails model attributes accessible using symbols instead of strings?
    text
    copied!<p>I need to compare some Rails (2.3.11) model attribute values before and after a database update, so I start by finding my record and saving the existing attribute values in a hash, as follows:</p> <pre><code>id = params[:id] work_effort = WorkEffort.find(id) ancestor_rollup_fields = { :scheduled_completion_date =&gt; work_effort.scheduled_completion_date } work_effort.update_attributes(params.except(:controller, :action)) #etcetera </code></pre> <p>Note I am adhering to the "best practice" of using a symbol for a hash key.</p> <p>Then I have a method that takes the model and the hash to determine possible additional steps to take if the values from the hash and the model attributes don't match. To determine this I tried to get at the model attribute value in an each loop but I was getting nil at first:</p> <pre><code>def rollup_ancestor_updates(work_effort, ancestor_rollup_fields) ancestor_rollup_fields.each do |key, value| model_val = work_effort.attributes[key] #nil #etcetera </code></pre> <p>In debugging the above I noticed that hard-coding a string as a key: </p> <pre><code>work_effort.attribute['scheduled_completion_date'] </code></pre> <p>Returned the desired value. So then in my each block I tried the following and it worked:</p> <pre><code>model_val = work_effort.attributes[key.to_s] </code></pre> <p>Is there a different way to do this? To me, with just 3 months Ruby/Rails experience, it's confusing to use symbols as hash keys as is the prescribed best practice, but then have to call .to_s on the symbol to get at a model attribute. Has anybody else experienced this, worked around this, been confused by this too? Thanks in advance</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload