[英]How to automatically update model with has_many through association?
我有 3 个模型:提供者(由 STI 从用户继承)、汽车和广告。 并有以下关联:
class Provider < User
has_many :advertisements, foreign_key: :user_id, dependent: :destroy
has_many :cars, through: :advertisements, foreign_key: :user_id, dependent: :destroy
end
class Car < ApplicationRecord
belongs_to :user
has_one :advertisement
end
class Advertisement < ApplicationRecord
belongs_to :user, foreign_key: :user_id
belongs_to :car, foreign_key: :car_id
end
我的架构如下所示:
create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
t.string "email", default: "", 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.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "type"
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
create_table "providers", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "cars", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
t.string "user_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.string "body_type"
t.string "brand"
t.string "fuel_type"
t.float "engine_capacity"
t.string "color"
end
create_table "advertisements", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
t.string "ad_type"
t.integer "user_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.integer "car_id"
t.text "description"
t.string "title"
end
一切正常,但是当我创建汽车实例时,我想看到相关的自动填充,例如: provider = current_user.cars 并且我看到空关系#<ActiveRecord::Associations::CollectionProxy []>
要解决此问题,我需要将以下内容添加到我的 Cars 控制器中:
def create
@car = Car.new(car_params)
current_user.cars << @car
respond_to do |format|
if @car.save
format.html { redirect_to cars_path, notice: 'Car was successfully created.' }
format.json { render json: @car, status: :created, location: @car }
else
format.html { render action: 'new' }
format.json { render json: @car.errors, status: :unprocessable_entity }
end
end
end
end
def car_params
params.require(:car).permit(:body_type, :model, :brand, :fuel_type, :engine_capacity, :condition, :color, :price, :year, :user_id)
end
但我认为这不是 Rails 方式,它应该由一些关联魔法自动填充。 请帮忙解决。
你应该做这样的事情:
def create
@car = current_user.cars.build(car_params)
....
end
然后 ActiveRecord 将负责设置对象之间的正确关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.