【发布时间】:2020-03-06 18:35:15
【问题描述】:
我有两个模型:User 和 Channel。有4种不同价格的频道:1000的动物频道,800的新闻频道等。每个用户可以订阅不同的频道,所以最终,我创建了三个具有以下关联的模型:
Channel
has_many :user_channels
has_many :users, through: :user_channels
User
has_many :user_channels
has_many :channels, through: :user_channels
UserChannel
belongs_to :user
belongs_to :channel
但我不确定这是正确的处理方式。
另外令人困惑的是,当我尝试将特定用户的频道价格设为user.user_channels.price 其中price 是Channel 的字段时,结果实际上是集合,这对我来说似乎是错误的,但又一次我只是在学习。
架构:
create_table "channels", force: :cascade do |t|
t.integer "category"
t.decimal "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "user_channels", force: :cascade do |t|
t.integer "user_id"
t.integer "channel_id"
t.decimal "spent_amount"
t.date "start_date"
t.date "due_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.string "email", default: "", null: false
t.boolean "admin", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
【问题讨论】:
-
那是因为你要求它为所有用户的频道。如果一个用户有很多渠道,而一个渠道有很多用户,你需要指定你要问哪个渠道的价格。您能否编辑您的问题并向我们展示您的架构,以便我查看您定义了哪些列?
-
感谢您的回复!一定要花点时间
-
@Beartech 我也添加了架构,谢谢!
标签: ruby-on-rails ruby model associations