afaf12
afaf12

Reputation: 5436

Couldn't find [model] without and id, Rails 3.2.3

I have followed the instructions and have tried to install simple-private-messages gem for Rails 3.2.3 .

I know there are many questions about "couldn't find [model] without an id", but they are slightly old and I've been unable to make solutions/ideas posted in any other questions work.

I've found the same problem and same gem being used in this question, but there is no clear answer provided. I also think the problem is not caused by the specific gem.

Steps I've done to install the plugin:

Added plugin to gemfile, ran bundle install
rails generate simple_private_messages:model User Pmessage
Added this line to user.rb : has_private_messages :class_name => "Pmessage"
rails generate simple_private_messages:scaffold User Pmessage
Uncommented this line in pmessage.rb : attr_accessor :to

I then added this to my routes.rb : match '/pmessages', to: 'pmessages#index'

Accessing /pmessages results in this error message:

ActiveRecord::RecordNotFound in PmessagesController#index Couldn't find User without an ID Rails.root: /home/user/RoR/railsapp app/controllers/pmessages_controller.rb:59:in `set_user'

pmessages_controller contains a set_user method which is the root of thee problem.

private
  def set_user
    @user = User.find(params:[user_id])
  end

I have a valid user record with id=1, but changing the troublesome line to @user = User.find(1) and accessing /pmessages results in this error message:

Showing /home/user/RoR/railsapp/app/views/pmessages/_inbox.html.erb where line #26 raised: undefined method `login' for #User:0xab4dc3c Extracted source (around line #26):

Assigning value to User this way or any other way still results in the same error message:

@user = User.first

Upvotes: 0

Views: 651

Answers (1)

Gosha A
Gosha A

Reputation: 4570

First, your route should be like

resources :users do
  resources :pmessages
end

So there is user_id on each request to /users/:user_id/pmessages.

Alternatively, your set_user method might look like:

def set_user
  @user = current_user
end

So @user always points to current user (and route can still be what you set it to).

Second, your User model has no field called login. If there is username attribute in your model, you might add this to the model: alias_attribute :login, :username or if you want the email to be login: alias_attribute :login, :email.

Upvotes: 1

Related Questions