ruby-on-railsrubymodelhas-many-throughassociated-object

Rails: How to not create new join models for newly associated objects


I'm working in Ruby on Rails 4.1.6. I have two associated models (Post and User) through another one (Comment).

User model:

class User < ActiveRecord::Base

  has_many :comments, dependent: :destroy
  has_many :posts, through: :comments
end

Post model:

class Post < ActiveRecord::Base

  has_many :comments, dependent: :destroy, :autosave => false
  has_many :users, through: :comments
end

Comment model:

class Comment < ActiveRecord::Base

  belongs_to :post, counter_cache: :comments_count
  belongs_to :user
end

When I'm creating new Post then new join model Comment with empty content. Is there any way to switch off that automatic creation?

EDIT:

I'm populating my database with sample_data.rake file like this:

.
.
.
users = neighborhood.users.limit(6)
category = PostCategory.find(1)
50.times do
  title = Faker::Lorem.sentence(1)
  content = Faker::Lorem.sentence(10)
  users.each { |user| user.posts.create!(title: title, content: content, neighborhood: neighborhood, user: user, post_category: category) }
end

And then when I'm creating new Post for User, comment is also created what I don't want.

EDIT 2:

In database it looks like this:

id  | user_id | post_id | content |         created_at         |         updated_at         
-----+---------+---------+---------+----------------------------+----------------------------
  1 |     100 |       1 |         | 2014-10-30 15:36:52.141408 | 2014-10-30 15:36:52.141408
  2 |      99 |       2 |         | 2014-10-30 15:36:52.173397 | 2014-10-30 15:36:52.173397
.
.
.
297 |      98 |     297 |         | 2014-10-30 15:37:00.184889 | 2014-10-30 15:37:00.184889
298 |      97 |     298 |         | 2014-10-30 15:37:00.215618 | 2014-10-30 15:37:00.215618
299 |      96 |     299 |         | 2014-10-30 15:37:00.237478 | 2014-10-30 15:37:00.237478
300 |      95 |     300 |         | 2014-10-30 15:37:00.258608 | 2014-10-30 15:37:00.258608

Solution

  • You have has_many :users, through: :comments association here so you can't create Post associated to User without creating join model - Comment. This is consequence of your data model.