My models:
class CountryVisit < ActiveRecord::Base
belongs_to :country
belongs_to :user
validates :country, uniqueness: { scope: user, message: 'already visited' }
end
class User < ActiveRecord::Base
has_many :country_visits
...
end
class Country < ActiveRecord::Base
has_many :country_visits
...
end
I want each country to have a virtual attribute indicating that it has country_visit for given user
Country.for(user)
Here's my incomplete solution (raises ActiveRecord::StatementInvalid: SQLite3::SQLException if I try to perform .count on result):
def self.for(user_id)
Country
.select("countries.*, country_visits.id AS visited")
.joins(
"LEFT OUTER JOIN country_visits ON
country_visits.country_id = countries.code
AND country_visits.user_id = #{user_id}"
)
end
Aucun commentaire:
Enregistrer un commentaire