简体   繁体   English

如何通过关联使用 has_many 自动更新模型?

[英]How to automatically update model with has_many through association?

I have 3 models: Provider (which is inherited from User by STI), Car and Advertisement.我有 3 个模型:提供者(由 STI 从用户继承)、汽车和广告。 And have following associations:并有以下关联:

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

My schema looks like this:我的架构如下所示:

  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

All works well but when I creating car instance I want to see auto population in relation such as: provider = current_user.cars and I see empty relation #<ActiveRecord::Associations::CollectionProxy []>一切正常,但是当我创建汽车实例时,我想看到相关的自动填充,例如: provider = current_user.cars 并且我看到空关系#<ActiveRecord::Associations::CollectionProxy []>

To fix this I need to add to my Cars controller following:要解决此问题,我需要将以下内容添加到我的 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

But I think this is not a Rails way and it should be auto populated by some associations magic.但我认为这不是 Rails 方式,它应该由一些关联魔法自动填充。 Please help to solve it.请帮忙解决。

You should do something like:你应该做这样的事情:

def create
    @car = current_user.cars.build(car_params)
  ....
end

Then ActiveRecord will take care of setting the right associations between the objects.然后 ActiveRecord 将负责设置对象之间的正确关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM