我的应用程序由3种型号组成:
FashionModel
Measurement
ModelProfile
class FashionModel < ActiveRecord::Base
has_secure_password
has_one :model_profile
has_one :measurement
accepts_nested_attributes_for :model_profile
accepts_nested_attributes_for :measurement
end
class ModelProfile < ActiveRecord::Base
belongs_to :fashion_model
end
class Measurement < ActiveRecord::Base
belongs_to :fashion_model
end
模式大致如下:
create_table "fashion_models", force: :cascade do |t|
t.string "first_name", limit: 25
t.string "last_name", limit: 25
t.string "email", limit: 255, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest", limit: 255
t.string "password_reset_token", limit: 255
t.datetime "password_reset_sent_at"
end
create_table "measurements", force: :cascade do |t|
t.integer "fashion_model_id", limit: 4
t.decimal "feet", precision: 10
t.decimal "inches", precision: 10
t.decimal "bust", precision: 10, default: 36
t.decimal "waist", precision: 10, default: 28
t.decimal "hips", precision: 10, default: 36
t.decimal "shoes", precision: 10
t.integer "dress", limit: 4
t.string "eyes", limit: 255
t.string "hair", limit: 255
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "model_profiles", force: :cascade do |t|
t.integer "fashion_model_id", limit: 4
t.string "phone_number", limit: 255
t.date "birthdate"
t.text "bio", limit: 65535
t.string "location", limit: 255, default: "Venice"
t.string "gender", limit: 255
t.decimal "rate", precision: 10, default: 100
t.string "profile_picture", limit: 255
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "model_profiles", ["fashion_model_id"], name: "index_model_profiles_on_fashion_model_id", using: :btree
add_foreign_key "bookings", "fashion_models"
add_foreign_key "fashion_model_photos", "fashion_models"
end
我正试图根据输入筛选出数据。例如,有人搜索身高5英尺8英寸、黑眼睛和棕色头发的模特,我应该通过查询数据库只显示这些模特
因此,我尝试在模型中使用命名作用域。我不确定如何通过在FashionModel
模型中写入范围来确定measurement
表的属性的范围。
我在网上阅读了一些资源,根据我的理解,我写了一些类似的东西
scope :eye_color, includes(:measurement).where(measurement: { eyes: "Amber" })
虽然我不想将Amber
硬编码到eyes字段中,但在尝试访问此作用域时,我在控制台中遇到了一个错误。我做一些类似的事情
a = FashionModel.all
a.eye_color
这给了我一个和ArgumentError: wrong number of arguments (given 0, expected 1)
。
我也试过做这个
scope :eye_color, -> (eye_color) { where eyes: eye_color }
然后用a.eye_color("Amber")
调用它,这反过来又给了我一个NoMethodError: undefined method 'measurement' for Class
。
因此,基本上我想从父模型扩展到子模型。非常感谢您的帮助!感谢
将您的范围定义为:
scope :eye_color, ->(eye_color) {
includes(:measurements).where(measurements: {eyes: eye_color})
}
然后使用以下参数进行查询:
FashionModel.eye_color("Amber")