egidra
egidra

Reputation: 9087

How to create a new Post through a User?

I have the following User and Post relationships:

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation

  has_many :posts
end


class Post < ActiveRecord::Base
  attr_accessible :content

  belongs_to :user
end

I am trying to create a new Post through a User, but I get an error. I am not sure why:

1.9.3-p392 :001 > @user = User.where(:id => 1)
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1
 => [#<User id: 1, email: "[email protected]", encrypted_password: "$2a$10$ltpBpN0gMzOGULVtMxqgueQHat1DLkY.Ino3E1QoO2nI...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 6, current_sign_in_at: "2013-03-04 05:33:46", last_sign_in_at: "2013-03-03 22:18:17", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2013-03-02 03:41:48", updated_at: "2013-03-04 05:33:46", avatar_file_name: nil, avatar_content_type: nil, avatar_file_size: nil, avatar_updated_at: nil>] 
1.9.3-p392 :002 > @user.posts.create(:content => "This is the content")
NoMethodError: undefined method `posts' for #<ActiveRecord::Relation:0x000000024ca868>

Upvotes: 1

Views: 82

Answers (3)

Ramiz Raja
Ramiz Raja

Reputation: 6030

Use this

@user = User.where(:id => 1).shift
@user.posts.create(:content => "This is the content")

OR

@user = User.find(1)
@user.posts.create(:content => "This is the content")

Upvotes: 0

sjain
sjain

Reputation: 23356

There is a difference between where and find in the ActiveRecord Relationships.

The query:

@user = User.where(:id => 1) is giving your the array hash.

So when you do something like @user.posts for the above query, it gives error of NoMethodError on ActiveRecord::Relation as there is no such post associated with this hash. So in order to convert it into the user whose id is 1, you do like this:

@user = User.where(:id => 1).first 

or

@user = User.find(:id => 1)

Both will give you the user whose id is 1 (only one record) and then you can use this:

@user.posts

The above will give the associated posts of user with id 1.

Then you can do:

@user.posts.create(:content => "Post of user 1")

So what you are trying to do is actually giving you the hash (set of users) but actually you want only one user to create the relevant post.

Also, See the difference between find and where.

Upvotes: 2

awendt
awendt

Reputation: 13723

Your code

User.where(:id => 1)

does not give you a model instance, but a relation. Hence the NoMethodError on ActiveRecord::Relation.

Change your first line to

User.find(1)

and you're fine.

Upvotes: 0

Related Questions