将新模型与用户ID相关联

时间:2014-11-03 20:22:02

标签: ruby-on-rails

我(非常)对ror很新,并且已经阅读了很多这个问题的教程,但似乎都没有。我试图让一个用户创建一个摊位来销售东西。

这是我的数据库迁移:

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时,它不会保存到数据库。当我将其排除时,它会保存,但不包括数据库中的用户ID。如果您还在阅读谢谢,我希望您能提供帮助!

1 个答案:

答案 0 :(得分:1)

您需要将create的{​​{1}}方法更改为:

BoothsController

在这里,您在用户和展位之间建立了一对一的关联,这就是为什么您必须使用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实例化current_user的原因,build_<singular_association_name> {1}}并将params传递给它:build_booth

build_booth(booth_params)适用于一对多关联,例如:用户有很多摊位,反之亦然。

相关问题