1

I have a User model (generated by devise) and a Submission model in a Rails project. I've added a field called 'full_name' to the user model. Also, there is a field for 'user_id' in the submission model.

I want to show the the full_name of the user associated with the submission on the submission show page. Right now it shows the user_id from the submission model just fine.

The User model I have this:

class User < ActiveRecord::Base
  has_many :submissions
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :confirmable

  attr_accessible :email, :password, :password_confirmation, :remember_me, :full_name, :role_id

  validates_presence_of :full_name
end

This is the model for submissions:

class Submission < ActiveRecord::Base
  belongs_to :user
  attr_accessible :description, :title, :user_id
end

This is in the controller:

  def show
    @submission = Submission.find(params[:id])
    @user = User.find(params[@submission.user_id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @submission }
    end
  end

What I get when I try to use this line in the view:

<%= @user.full_name %>

I get this error:

Couldn't find User without an ID

I've tried several variations and can't quite figure out what should be in the place of:

@user = User.find(params[@submission.user_id])

1 Answer 1

2

Assuming that you're populating the data correctly, you only need the following once you have looked up the submission.

@submission.user

If you think that the data is OK, then try the following in the Rails console.

> Submission.first.user

What do you see there?


The specific error that you are seeing is because this:

params[@submission.user_id]

is unlikely to ever have anything in it. If the user ID is "1" (for example) then you're asking for the value in the params hash that corresponds to the key "1".

Sign up to request clarification or add additional context in comments.

1 Comment

It's a problem with my data. Thanks for suggesting looking in the console. The first User in my database has the id of 3 and the user_id in the submission has value of 1. When I change the user_id in the data to 3 and change the view to read: @submission.user.full_name instead it works. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.