我是rails的新手,所以任何帮助都会非常感激。我有模型用户和广告。用户has_many广告和广告属于用户。
问题:当用户创建广告时,我希望创建的广告自动链接到创建广告的当前用户。我不确定如何去做这个
我知道如何在控制台中为用户分配广告
advert = Advert.first
advert.userr_id = 3
advert.save
但我不确定如何在我的控制器中实现它。非常感谢任何方向建议
模式
ActiveRecord::Schema.define(version: 20150330233948) do
create_table "adverts", force: true do |t|
t.string "title"
t.text "content"
t.integer "category_jobtype_id"
t.integer "category_positiontype_id"
t.integer "salarystart"
t.integer "salaryend"
t.integer "category_country_id"
t.string "city"
t.string "town"
t.string "postcode"
t.integer "category_editorialapproval_id"
t.integer "category_applicationrequest_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "userr_id"
end
create_table "userrs", force: true 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.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.string "firstname"
t.string "lastname"
t.string "companyname"
t.integer "category_businesstype_id"
end
add_index "userrs", ["email"], name: "index_userrs_on_email", unique: true
add_index "userrs", ["reset_password_token"], name: "index_userrs_on_reset_password_token", unique: true
end
模型
class Advert < ActiveRecord::Base
belongs_to :user
end
class Userr < ActiveRecord::Base
has_many :adverts
end
控制器:广告
class AdvertsController < ApplicationController
respond_to :html, :xml, :json
before_action :set_advert, only: [:show, :edit, :update, :destroy]
def index
@adverts = Advert.all
respond_with(@adverts)
end
def show
respond_with(@advert)
end
def new
@advert = Advert.new
respond_with(@advert)
end
def edit
end
def create
@advert = Advert.new(advert_params)
@advert.save
respond_with(@advert)
end
def update
@advert.update(advert_params)
respond_with(@advert)
end
def destroy
@advert.destroy
respond_with(@advert)
end
private
def set_advert
@advert = Advert.find(params[:id])
end
def advert_params
params.require(:advert).permit(:title, :content, :category_jobtype_id, :category_positiontype_id, :salarystart, :salaryend, :category_country_id, :city, :town, :postcode, :category_editorialapproval_id, :category_applicationrequest_id)
end
end
controller:Userr
任何帮助将不胜感激。书籍推荐或教程将有所帮助....非常感谢
答案 0 :(得分:0)
一旦您可以访问用户对象,基本上就可以这样做:
def create
@advert = Advert.create(advert_params)
user.adverts << @advert
respond_with(@advert)
end
当您使用has_many
方法时,模型会“免费”接收一些方法。 <<()
方法只是其中之一。您可以找到很多关于关联的信息,这些方法会自动生成here。