Kelly
Kelly

Reputation: 469

Associating new model with user id

I'm (very) new to ror and have read many tutorials for this issue but none seem to work. I'm trying to let one user create one booth to sell things.

This is my db migration:

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

Here is the booth controller:

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

And this is the booth model:

class Booth < ActiveRecord::Base
  belongs_to :user
  validates :user_id, presence: true

end

I also added this to the user model:

has_one :booth, dependent: :destroy

When I include validates :user_id, presence: true it won't save to the db. When I exclude it, it saves but does not include a user id in the database. If you are still reading thank you and I hope you can help!

Upvotes: 0

Views: 48

Answers (1)

Surya
Surya

Reputation: 15992

You need to change create method of your BoothsController to this:

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

Here, you have one-to-one association between user and booth, and that's why you have to instantiate booth for current_user using build_<singular_association_name>, which is build_booth and pass params to it: build_booth(booth_params).

booths.build(booth_params) works for one-to-many association, for example: user has many booths, not vice a versa.

Upvotes: 1

Related Questions