我對ror非常新,並且已經閱讀了許多關於此問題的教程,但似乎沒有任何工作。我試圖讓一個用戶創建一個展位來銷售東西。將新模型與用戶ID關聯起來
這是我的數據庫遷移:
class CreateBooths < ActiveRecord::Migration
def change
create_table :booths do |t|
t.string :name
t.references :user, index: true
t.timestamps null: false
end
add_index :booths, [:user_id]
end
end
這裏的攤位控制器:
class BoothsController < ApplicationController
before_action :logged_in_user
def new
@booth = Booth.new
end
def create
@booth = current_user.booths.build(booth_params)
if @booth.save
flash[:success] = "Congrats on opening your booth!"
redirect_to root_url
else
render 'new'
end
end
private
def booth_params
params.require(:booth).permit(:name)
end
end
而這展位模型:
class Booth < ActiveRecord::Base
belongs_to :user
validates :user_id, presence: true
end
我也已將此添加用戶型號:
has_one :booth, dependent: :destroy
當我包括validates :user_id, presence: true
它不會保存到數據庫。當我排除它時,它會保存,但不包括數據庫中的用戶標識。如果你還在讀感謝,我希望你能幫助!
'current_user'是否有'id'? – ptd 2014-11-03 20:27:00
@ptd:如果'current_user'不可用,那麼OP會問:爲什麼沒有定義的方法'booths'爲零類。 :) – Surya 2014-11-03 20:29:55
@ptd是的,當前用戶有ID。下面的答案效果很好。謝謝。 – Kelly 2014-11-05 02:45:07