我对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