开发者

how to fetch values in self.find after using :from in rails

开发者 https://www.devze.com 2022-12-22 08:50 出处:网络
players_data =self.find(:all, :order => \'name\', :conditions => \'p.country = c.id and p.position = po.id\',
players_data =  self.find(:all,
  :order => 'name',
  :conditions => 'p.country = c.id and p.position = po.id',
  :select => 'p.id as id, p.name as name, c.country as country, po.position as position, p.rank as rank',
  :from => 'players as p, countries as c, positions as po'
)

--------------------------------

players_data.each do |row| #puts " The Row === #{row.country}" tmpArray = [] tmpArray[0] = row.id tmpArray[1] = row.name tmpArray[2] = row.country tmpArray[3] = row.position tmpArray[4] = row.rank

I'm unable to get the values 开发者_开发技巧for country and position. Please suggest.


You seem to be mixing straight SQL logic with ActiveRecord logic and getting undesirable results. Consider using Associations instead:

class Country < ActiveRecord::Base
end

class Position < ActiveRecord::Base
end

class Player < ActiveRecord::Base
  belongs_to :country
  belongs_to :position
end

players = Player.find(:all)
players.each do |player|
  puts player.country.name
  puts player.position.rank
end

If you want to use Rails conventions, define the foreign keys as table_id (i.e. a Player has a country_id and position_id column). This allows for the Association magic to work.

If you are working with legacy database tables, you can further specify the associations following the ActiveRecord Associations API.

0

精彩评论

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

关注公众号