简体   繁体   中英

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. 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 []>

To fix this I need to add to my Cars controller following:

    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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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