Reputation: 2227
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])
Upvotes: 1
Views: 85
Reputation: 17790
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".
Upvotes: 2