0

so basically I have two models:

class User < ActiveRecord::Base
  has_and_belongs_to_many :post
end

class Post < ActiveRecord::Base
  has_and_belongs_to_many :user
end

and my migration was:

rails g migration CreateJoinTablePostsUsers posts users

But in my console if I type:

@post = Post.where(:id => User.find_by_email("me@mail.com").post_ids).last

but I get nil instead

I checked in the terminal:

Post.last.user_ids

and:

User.last.post_ids

both of them returned empty

J.Foe
  • 43
  • 4
  • 2
    What are you doing to create the `PostUser` entry in the database? – Okomikeruko Aug 11 '17 at 20:42
  • forgot about that – J.Foe Aug 11 '17 at 21:15
  • Rails will only automatically create a join row if you create the records from one end. eg `Post.last.users.create`. I'm a bit unsure if you don't just have the wrong type of association. What is the actual use case? – max Aug 11 '17 at 21:23
  • @Okomikeruko since the association is `has_and_belongs_to_many` there is no `PostUser` model. Rather just rows in the `users_posts` join table. – max Aug 11 '17 at 21:26
  • Could you also post the contents of the migration that was generated? There is no intermediate model here, perhaps your join table wasn't created correctly? – Prajjwal Aug 12 '17 at 11:10

1 Answers1

0

This question has been answered before here: Add record to a has_and_belongs_to_many relationship.

Basically, you need to assign values to one another.

post = Post.find(x)
user = User.last
user.posts << post

They're returning empty because they are empty and need their values to be assigned.

Okomikeruko
  • 1,123
  • 10
  • 22