在我的Rails應用程序中,我只需要用戶在註冊時輸入電子郵件和姓名,然後給他們選項以提供他們個人資料的更詳細聯繫人詳細信息。因此,我有與Contact.rb,即關聯一個User.rb模型,如何通過has_one關聯加入關聯的表
User.rb
has_one :contact
Contact.rb
belongs_to :user
Contact.rb具有可預測您可能需要的字段,例如地址,郵政編碼等,但它也存儲與Province.rb模型關係的province_id,因此
Contact.rb
attr_accessible :address, :city, :mobile, :postalcode, :province_id, :user_id
belongs_to :user
belongs_to :province
Province.rb
has_many :contacts
我做了這樣的說法(而不是存儲省的名稱作爲contact.rb一「串」),這樣我可以更容易地(所以我想)按省分類用戶。
在artists_controller之一的show行爲,我這樣做檢查用戶是否正試圖通過省排序,然後調用,它搜索
if params[:province_id]
province = params[:province_id]
province = province.to_i #convert string to integer
@artistsbyprovince = User.artists_by_province(province)
else
@artists = User.where(:sculptor => true)
end
這是該方法的artists_by_province方法對,如果一個省的ID在
scope :artists_by_province, lambda {|province|
joins(:contact).
where(contact: {province_id: province},
users: {sculptor: true})
}
但是它給了我這個錯誤通過調用User.rb型號:
Could not find table 'contact'
如果我進行接觸多
scope :artists_by_province, lambda {|province|
joins(:contacts).
where(contacts: {province_id: province},
users: {sculptor: true})
}
此錯誤
Association named 'contacts' was not found; perhaps you misspelled it?
誰能告訴我,我做錯了什麼,當我在做這個查詢?
更新:我改變了一些細節後發佈,因爲我的複製和粘貼了一些問題,它
附:無視我正在尋找「雕塑家」的事實。我更改了問題的用戶類型的名稱。
從schema.rb
create_table "contacts", :force => true do |t|
t.string "firm"
t.string "address"
t.string "city"
t.string "postalcode"
t.string "mobile"
t.string "office"
t.integer "user_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.integer "province_id"
end
,給了我這個錯誤:協會命名爲 'province_id' 沒有被發現;也許你拼錯了嗎? – Leahcim 2013-05-03 02:00:34
請查看我更新的帖子 – 2013-05-03 05:43:23
我對此並不是很有經驗。你的解決方案比我的更好嗎?如果是這樣,你能解釋爲什麼嗎?謝謝。 – Leahcim 2013-05-03 13:35:17