2014-11-03 32 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

相关问题