0
我是新來的鐵軌,所以任何幫助將不勝感激。我有模特用戶和廣告。用戶has_many廣告和廣告屬於用戶。Active Records - Userr_id - rails 4
問題:當用戶創建廣告時,我希望創建的廣告自動鏈接到創建廣告的當前用戶。我不知道該如何去這
我知道如何在廣告控制檯
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
控制器:Userr
任何幫助都會爲m非常感謝。書建議或教程會有所幫助....非常感謝
謝謝@Tiago,但它似乎沒有工作。當用戶創建廣告時,它不會將用戶分配給廣告。廣告在控制檯中仍然有一個user_id,表示爲'nil' – ARTLoe 2015-04-02 10:44:51