2014-11-03 31 views
0

我對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它不會保存到數據庫。當我排除它時,它會保存,但不包括數據庫中的用戶標識。如果你還在讀感謝,我希望你能幫助!

+0

'current_user'是否有'id'? – ptd 2014-11-03 20:27:00

+1

@ptd:如果'current_user'不可用,那麼OP會問:爲什麼沒有定義的方法'booths'爲零類。 :) – Surya 2014-11-03 20:29:55

+0

@ptd是的,當前用戶有ID。下面的答案效果很好。謝謝。 – Kelly 2014-11-05 02:45:07

回答

1

你需要改變你的BoothsControllercreate方法是:

def create 
    @booth = current_user.build_booth(booth_params) 
    if @booth.save 
    flash[:success] = "Congrats on opening your booth!" 
    redirect_to root_url 
    else 
    render 'new' 
    end 
end 

在這裏,你有用戶和攤位之間的一個一對一的關聯,這就是爲什麼你必須實例booth使用build_<singular_association_name>current_user爲,它是build_booth並將params傳遞給它:build_booth(booth_params)

booths.build(booth_params)適用於一對多關聯,例如:用戶有許多展位,而不是反之亦然。

+0

感謝百萬人,這就像一個魅力,我很欣賞的解釋。 – Kelly 2014-11-03 22:01:36

相關問題