如何使用has_one关联连接关联表
在我的Rails应用程序中,我只要求用户在注册时输入电子邮件和姓名,然后为他们提供选项,以便为他们的个人资料提供更全面的联系详细信息。 因此,我有一个User.rb模型,它与Contact.rb有关联,即
User.rb
has_one :contact
Contact.rb
belongs_to :user
Contact.rb具有您可能期望的可预测字段,例如地址,邮政编码等,但它也存储了省份与省份.rb模型的关系,所以
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动作中,我执行以下操作来检查用户是否尝试按省排序,然后调用一个执行搜索的artists_by_province方法
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
这是User.rb模型上的方法,如果传入省id,它将调用该方法
scope :artists_by_province, lambda {|province| joins(:contact). where( contact: {province_id: province}, users: {sculptor: true}) }
但它给了我这个错误:
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?
当我进行此查询时,有人能告诉我我做错了什么吗?
更新:我发布后更改了一些细节因为我的复制和粘贴有一些问题
PS忽略了我正在寻找“雕塑家”的事实。 我更改了问题的用户类型的名称。
来自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
通过在联接中使用contact
(单数)和在where子句中使用contacts
(复数)来解决问题。 我猜’contact’(单数)反映了User.rb和Contact.rb之间的has_one关联,而’contacts’在where子句中用来表示表的名称,该表总是复数。
User.rb
has_one :contact scope :artists_by_province, lambda {|province| joins(:contact). where( contacts: {province_id: province}, users: {sculptor: true}) }
你可以试试以下吗?
scope :artists_by_province, lambda {|province| joins(contact: {province: { id: province}}). where(sculptor: true) }