0

我正在使用 Ruby on Rails 4.1.6。我通过另一个(评论)有两个关联的模型(帖子和用户)。

用户型号:

class User < ActiveRecord::Base

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

岗位型号:

class Post < ActiveRecord::Base

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

评论型号:

class Comment < ActiveRecord::Base

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

当我创建新帖子时,然后新加入模型评论,内容为空。有什么办法可以关闭自动创建?

编辑:

我正在使用这样的 sample_data.rake 文件填充我的数据库:

.
.
.
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

然后当我为用户创建新帖子时,也会创建我不想要的评论。

编辑2:

在数据库中它看起来像这样:

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
4

1 回答 1

1

您在has_many :users, through: :comments这里有关联,因此您无法在不创建连接模型的情况下创建Post关联- 。这是您的数据模型的结果。UserComment

于 2014-10-30T16:06:28.880 回答