0

I'm trying to set all the values to 0 but the 3rd line (send(x)) is giving me problems. Seems right to me, but doesn't work. x is the car and name of the columns in Power. Any tips?

<% @cars.each do |x| %>
  <% @power = Power.find_by_user_id(@user) %>
  <% @power.send(x) = 0 %>
  <% @power.save %>
<% end %>
7
  • what exactly is the value of cars? Commented Sep 9, 2012 at 16:51
  • What do you mean "all the values"? Also this should definitely not be in a view (assuming this is Rails-like). Commented Sep 9, 2012 at 16:51
  • say the @cars array contains c01 c02 c03 etc, and those are the names of the columns Commented Sep 9, 2012 at 16:51
  • @andrew, yea I'm going to clean this up and take it out of the view, i'm just getting it to work first Commented Sep 9, 2012 at 16:52
  • 1
    If I recall correctly past questions, you tend to set @vars in views, that's not idiomatic, use local variables. And never, ever, a save in a view. Commented Sep 9, 2012 at 16:52

1 Answer 1

2

Assuming @cars contains column names of Power, you need to send the setter method (i.e. with an = at the end). You also need to ensure you're passing a symbol to send.

@cars.each do |x|
  @power = Power.find_by_user_id(@user)
  @power.send(:"#{x}=", 0)
  @power.save
end

There's also not an obvious reason why you need to set or save @power in the loop, so it might be better as:

@power = Power.find_by_user_id(@user)
@cars.each do |x|
  @power.send(:"#{x}=", 0)
end
@power.save
Sign up to request clarification or add additional context in comments.

2 Comments

Is it the only way to access dynamic attribute name? Does ActiveRecord class have method like @power.get_attribute_by_name(x)?
@galymzhan There is write_attribute, but that will bypass any custom-defined writer in the model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.