views:

37

answers:

1

I'm using Ruby on Rails and the paths_of_glory gem

I need to access the types of achievements that a user accomplishes in order to display a picture along with each particular achievement. When I try to access it via @user.achievements.type, I get an error that says that it wants to return "array" (as in achievements is an array) instead of actually returning the elements in the type column of my database.

Since every ruby object has a method called type, my call to access the type column of the database fails. When I try to change the entry in the table, the paths_of_glory gem says it needs a type column in order to function properly.

I'm not quite sure where to go from here in order to access that column in the database. Any suggestions?

+3  A: 

Not entirely sure what you're asking here, but maybe this will help.

For the first thing, @user.achievements is an array because you have multiple achievements, and the type method is for individual elements of @user.achievements which is why that won't work just like that. You'll have to do something like this:

@user.achievements.each do |achievement|
  # Do stuff here
end

Regarding the type column, type is a reserved column in Rails used specifically for Single Table Inheritance, where multiple Rails models use a single database table. So you can't access it directly. I assume that paths_of_glory uses STI in some manner. You can access the model's class with something like achievement.class, then if you want just the name of it you can try achievement.class.to_s.

@user.achievements.each do |achievement|
  model = achievement.class # => MyAwesomeAchievementClass
  @image = model.picture    # You could write some method in the model like this
end
Karl
Steve Weet
When I try to run @user.achievements.each do |achievement|, it gives me the error:The single-table inheritance mechanism failed to locate the subclass. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite Achievement.inheritance_column to use another column for that information.
jfedick
Did you try to do anything inside the block or is it erroring on just that line?
Karl
I do stuff in the block, but the error says it comes from that line in particular.
jfedick
Can you edit your original post with the block and the error / stack trace? Also, try running it once without doing anything inside the block, just as a control case.
Karl