我的模型:布爾字段表明記錄與給定的字段值屬於關聯
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
我想每個國家有一個虛擬屬性表明它具有country_visit
給定用戶
Country.for(user)
這是我的不完整的解決方案(提高ActiveRecord::StatementInvalid: SQLite3::SQLException
如果我試圖執行.count
的結果):
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
預期的行爲:
user = User.create
#with country visit
c1 = Country.create
cv1 = CountryVisit.create(country: c1, user: user)
#without country visit
c2 = Country.create
結果應該是:
countries = Country.for(user_id).order('created_at asc')
countries.first.visited # => true
countries.last.visited # => false
我不明白,結果你想從這個查詢得到什麼? – Fenec 2015-04-04 14:36:28
@ Fenec我的不好。更新了**預期行爲的問題** – 2015-04-04 14:45:51