Question

rails -v = 4.0
ruby -v = 2.1.1

I am having some serious problem with has_one :through. All of the google 1st 2 pages link are blue in color ( I have gone through all of them).

My problem is when I try to do

post = Post.last
post.build_user

It say undefined method `build_user'. My classes with associations are as follow.

class Post < ActiveRecord::Base    
    has_one :user_post
    has_one :user, class_name: "User", through: :user_post

   accepts_nested_attributes_for :user
end

class UserPost < ActiveRecord::Base
    belongs_to :user
    belongs_to :post
end

class User < ActiveRecord::Base
    has_many :user_posts
    has_many :posts, through: :user_posts 
end

It would be really great if somebody please help to out to resolve this issue.

Much obliged.

Was it helpful?

Solution

You are attempting to setup a Many-to-Many Relationship between Post and User but your current setup is incorrect.

You need to use has_many instead of has_one in Post model.

class Post < ActiveRecord::Base    
  has_many :user_posts
  has_many :users, through: :user_posts
end

After this you can build the users as:

post = Post.last
post.users.build

UPDATE

You are getting error as undefined methodbuild_user'.because you can only usepost.build_userif association betweenPostandUserishas_one` and defined as below:

class Post < ActiveRecord::Base
  has_one :user
end
class User < ActiveRecord::Base
  belongs_to :post    # foreign key - post_id
end

UPDATE 2

Also, logically A user has_many posts AND A post has one User so your setup should ideally be

class Post < ActiveRecord::Base
  belongs_to :user   # foreign key - user_id
end
class User < ActiveRecord::Base
  has_many :posts    
end

After this you can build the posts for a user as:

user = User.last
user.posts.build

To build a user for a post:

post = Post.last
post.build_user
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top