Ruby on rails 如何将关联表与has_one关联
在我的Rails应用程序中,我只要求用户在注册时输入电子邮件和姓名,然后让他们选择为他们的个人资料提供更完整的联系方式。因此,我有一个User.rb模型,它与Contact.rb有关联,即 User.rbRuby on rails 如何将关联表与has_one关联,ruby-on-rails,Ruby On Rails,在我的Rails应用程序中,我只要求用户在注册时输入电子邮件和姓名,然后让他们选择为他们的个人资料提供更完整的联系方式。因此,我有一个User.rb模型,它与Contact.rb有关联,即 User.rb has_one :contact has_one :contact scope :artists_by_province, lambda {|province| joins(:contact). where( contacts: {province_id: provinc
has_one :contact
has_one :contact
scope :artists_by_province, lambda {|province|
joins(:contact).
where( contacts: {province_id: province},
users: {sculptor: true})
}
Contact.rb
belongs_to :user
attr_accessible :address, :city, :mobile, :postalcode, :province_id, :user_id
belongs_to :user
belongs_to :province
Contact.rb具有您可能期望的可预测字段,如地址、邮政编码等,但它还存储与provide.rb模型的关系的省id,因此
Contact.rb
belongs_to :user
attr_accessible :address, :city, :mobile, :postalcode, :province_id, :user_id
belongs_to :user
belongs_to :province
省.rb
has_many :contacts
我就是这样做的(而不是在contact.rb上以“字符串”的形式存储省名),这样我就可以更容易地(所以我认为)按省对用户进行分类
在其中一个artists_控制器的show操作中,我执行以下操作以检查用户是否尝试按省份排序,然后调用执行搜索的artists_by_省份方法
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?
有谁能告诉我,当我提出这个问题时,我做错了什么
更新:我在发布后更改了一些细节,因为我的复制和粘贴有一些问题
另外,忽略我正在搜索一个“雕塑家”的事实。我为这个问题更改了用户类型的名称
从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
你能试试下面的吗
scope :artists_by_province, lambda {|province|
joins(contact: {province: { id: province}}).
where(sculptor: true)
}
通过在join中使用
contact
(单数)和在where子句中使用contacts
(复数)解决了该问题。我猜“contact”(单数)反映User.rb和contact.rb之间的has_one关联,而“contacts”在where子句中用于表示表名,它总是复数的
User.rb
has_one :contact
has_one :contact
scope :artists_by_province, lambda {|province|
joins(:contact).
where( contacts: {province_id: province},
users: {sculptor: true})
}
这给了我这个错误:找不到名为'province_id'的关联;也许你拼错了?我对这方面不是很有经验。你的解决方案比我的好吗?如果是,你能解释一下原因吗?谢谢。你的是有效的。在控制台中尝试这两种方法,看看它们的区别。是的,这也是我所理解的。顺便说一句,我的帖子对您没有任何用处,因为它将在左侧join子句上生成province_id条件,从而生成所有用户的sculptor=true。