在我的 Rails 应用程序中,我只要求用户在注册时输入电子邮件和姓名,然后让他们可以选择为其个人资料提供更完整的联系方式。因此,我有一个与 Contact.rb 关联的 User.rb 模型,即
User.rb
has_one :contact
联系方式.rb
belongs_to :user
Contact.rb 具有您可能期望的可预测字段,例如地址、邮政编码等,但它还存储与 Province.rb 模型关系的province_id,因此
联系方式.rb
attr_accessible :address, :city, :mobile, :postalcode, :province_id, :user_id
belongs_to :user
belongs_to :province
省份.rb
has_many :contacts
我就是这样做的(而不是将省份名称存储为 contact.rb 上的“字符串”),以便我可以更轻松地(所以我认为)按省份对用户进行分类。
在 Artist_controller 之一的显示操作中,我执行以下操作来检查用户是否尝试按省排序,然后调用 Artist_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?
谁能告诉我当我进行此查询时我做错了什么?
更新:我在发布后更改了一些细节,因为我的复制和粘贴有一些问题
附:忽略我正在寻找“雕塑家”的事实。我更改了问题的用户类型的名称。
来自 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