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

0sgqnhkj  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(277)

我有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 []> 要解决此问题,我需要在我的汽车控制器中添加以下内容:

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的方式,它应该由一些神奇的关联自动填充。请帮忙解决它。

jrcvhitl

jrcvhitl1#

你应该这样做:

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

然后activerecord将负责设置对象之间的正确关联。

相关问题