3

On Rails 3.2.1. I have a model called Car with an attribute called rate (indicates a price quantity). I'm using the ajaxful_rating gem which associates a method called rate (to submit a rating of how good a teacher is) with a Car.

So in my view, when I'm trying to show a price quantity with:

<%= @car.rate %>

I get a syntax error because there's naming confusion. How do I let Rails know that I want to call the rate attribute and not the rate method? Is there an easy way to resolve this without rolling back my DB and renaming the attribute?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214

2 Answers2

1

Well, first of all, you wouldn't have to roll back the database to rename the attribute. You would just create a new migration with this one change: How can I rename a database column in a Ruby on Rails migration? Those kinds of changes are necessary from time to time and so Rails has this mechanism for handling them.

But to answer your question, an alternate workaround would be to write a new method on car which actually gives access to the attribute like this:

def rate_price
  read_attribute(:rate)
end
Community
  • 1
  • 1
Dogweather
  • 15,512
  • 17
  • 62
  • 81
  • Thanks for the suggestion and the migration article link! Being fairly new to rails, I see the other poster's point about confusing myself down the road, although having to go that way it'll affect my rspec tests a bit. –  Mar 12 '12 at 21:44
  • Your syntax is incorrect, `read_attribute` is a method with an argument, not an array. – Andrew Marshall Mar 12 '12 at 21:45
1

You can use read_attribute:

@car.read_attribute(:rate)

but I suggest that you resolve the conflict by renaming one of them as it will just cause you problems and confusion down the road.

You don't need to rollback your database to rename a column, you just have to create a new migration that does so.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • Thanks, I'm still fairly new to rails so I think you're right about the confusion part...Interesting, I never knew about read_attribute(). –  Mar 12 '12 at 21:45