Reputation: 1737
This is a very basic task, but I can't for the life of me find the cause of the issue.
I am doing a basic to-do lists attached to user accounts. I am using Sorcery to help with the user authentication & creation, which seemingly works fine.
The Problem Is This:
When I try to call `@user.list' in any way, I get the following exception (this is copied out of the rails console):
@user = User.where(:email => "[email protected]")
=> [#<User id: 1, email: "[email protected]", crypted_password: "$2a$10$tiLFyiuLGSB.UXElEdaTGerSv6/TZoLL4nVFdCNsv1AW...", salt: "e6275124385b0ea157875bba281c7ae9e3a9858e", created_at: "2011-10-02 05:59:02", updated_at: "2011-10-02 05:59:02", remember_me_token: nil, remember_me_token_expires_at: nil>]
@user.lists
NoMethodError: undefined method `lists' for #<ActiveRecord::Relation:0x007f8b6ca89748>
from /Users/<myaccount>/.rvm/gems/[email protected]/gems/activerecord- 3.1.0/lib/active_record/relation.rb:459:in `method_missing'
from (irb):4
from /Users/<myaccount>/.rvm/gems/[email protected]/gems/railties-3.1.0/lib/rails/commands/console.rb:45:in `start'
from /Users/<myaccount>/.rvm/gems/[email protected]/gems/railties-3.1.0/lib/rails/commands/console.rb:8:in `start'
from /Users/<myaccount>/.rvm/gems/[email protected]/gems/railties-3.1.0/lib/rails/commands.rb:40:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
My Code/DB Setup
The setup is simple - I have a User
model and a List
model. a List
:belongs_to :user
, and a User
has_many :lists
. I have added user_id
to the lists
table with the following migration:
class AddUserIdForeignKeyToLists < ActiveRecord::Migration
def change
add_column :lists, :user_id, :integer
end
end
I have confirmed that the field user_id
does exist in my table (MySQL).
My User
model is:
class User < ActiveRecord::Base
has_many :lists
authenticates_with_sorcery!
attr_accessible :email, :password, :password_confirmation
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
end
... and my List
model looks like this:
class List < ActiveRecord::Base
belongs_to :user
end
The table design view from MySQL is as follows:
users
:
lists
:
This sounds to me like there might be a relationship issue, but I can't seem to put this together. Does anyone have any insight? I've never run into any trouble at all like this running Rails 3.0.X on a linux machine, but this is my first foray into Rails 3.1 on OSX, so I'm not sure if maybe I overlooked an underlying change?
Thanks for any guidance
Upvotes: 2
Views: 1436
Reputation: 21572
User.where(...)
returns a collection of User objects, not a User object. You need to get a User object.
@user = User.where(...).first
or, better
@user = User.find_by_email("[email protected]")
Upvotes: 5