user4965201
user4965201

Reputation: 973

Ruby on rails fetch name and show from the has many through

we have user table and also wee have a country table the association is given as

user.rb

has_many :user_countries
has_many :countries, :through => :user_countries


user_country.rb

belongs_to :user
belongs_to :country

country.rb

has_many :users, :through => :user_countries

now what i want is to fetch the country name and show it into the sql record such that the new user_country column should come which will show the country of the user while fetching users

data = User.select("users.*, countries.name as country_name").
            joins("INNER JOIN `user_countries` ON `user_countries`.`user_id ` = `users`.`id`").
            joins("INNER JOIN `countries` ON `countries`.`id ` = `user_countries`.`country_id`")

till now i am trying to do this but not succeeded it throws the mysql error . i need an extra column giving country_name as extra column. Please help me with this

Upvotes: 0

Views: 100

Answers (2)

Md. Farhan Memon
Md. Farhan Memon

Reputation: 6121

since you already using activerecord associations, you can use active record query as the following:

User.joins(:countries).select("users.*, countries.name as country_name")

You can learn more about select here

Upvotes: 1

Ivan Arambula
Ivan Arambula

Reputation: 124

Looks like you're trying to create a many to many relationship. This can be done very simply with a has_and_belongs_to_many association. Take a look at http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association.

Upvotes: 0

Related Questions