0

In my Rails 3.2 application, I have three ActiveRecord models, Post PostTag and Tag. PostTag is a link table (only contains foreign keys to the others).

There are several existing Tag records. I manually assign a collection of Tag records to Post as follows in my posts_controller.create method:

tags = Tag.all
@post.tags = tags

When I save, it runs my custom validation method in Tag as if it were creating new Tag records, even though I am simply linking Tag records to the new Post. I also have no validates_associated declared in Post. Models:

Post:
has_many :tags, :through => :post_tags
has_many :post_tags

PostTag:
belongs_to :post
belongs_to :tag

Tag:
has_many :posts, :through => :post_tags
has_many :post_tags

validate :validate_something

def validate_something
  ...
end

I have tried using << instead of = in the assignment above as per the ActiveRecord documentation, but no luck.

4

1 回答 1

0

I believe you encounter this problem since your association is :through => :post_tags. You need to create new PostTag elements to keep the links. Try this:

Tag.all.each { |tag| PostTag.create!(tag: tag, post: @post) }

Alternatively, you can try to port to has_and_belongs_to_many association, which abstracts PostTag away.

于 2014-04-10T06:44:29.563 回答