【发布时间】:2016-07-26 23:15:07
【问题描述】:
我的应用由 3 个模型组成:
FashionModelMeasurement 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 硬编码到 eye 字段中,但在尝试访问此范围时,我的控制台中出现错误。我做类似的事情
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。
所以基本上我想从父模型扩展到子模型。 任何帮助深表感谢!谢谢
【问题讨论】:
标签: mysql ruby-on-rails ruby mysql2