开发者

Type method interfering with database type column problem

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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜