Dylan Richards
Dylan Richards

Reputation: 708

User returning nil. Not sure what to do

I am trying to display the name of the user who posted an item. Only thing is that Item.last.user == nil.

I've set up the has_many and belongs_to relationships in the models already.

Here is the params hash of the items controller:

def item_params
  params.require(:item).permit(:name, :quantity, :boughtfor, :soldfor, :user_id)
end

Notice that I :user_id is there.

Schema for items:

  create_table "items", force: true do |t|
    t.string   "name"
    t.integer  "quantity"
    t.integer  "boughtfor"
    t.integer  "soldfor"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

How can I make the user not nil?

UPDATES

create action in items controller:

  def create
    @item = Item.new(item_params)

    respond_to do |format|
      if @item.save
        format.html { redirect_to @item, notice: 'Item was successfully created.' }
        format.json { render action: 'show', status: :created, location: @item }
      else
        format.html { render action: 'new' }
        format.json { render json: @item.errors, status: :unprocessable_entity }
      end
    end
  end

Upvotes: 0

Views: 55

Answers (2)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Do this way

@item = current_user.items.new(item_params)

This will take id of the current user. current_user refers to the signed in user

Upvotes: 3

Cremz
Cremz

Reputation: 838

when you create the migration you can setup

 t.integer  "user_id", null: false

or you can define the relation on the database level:

t.belongs_to :user, index: true

make sure you actually have the user id when you are trying to create the item. Are you using a form? How are you grabbing the user id? Is it from devise?

Upvotes: 0

Related Questions