singpolyma
singpolyma

Reputation: 11241

Implicitly create associated model from string

I have a model Post that has_many :tags

I want to do:

Post.create({:tags => ['tag1', 'tag2']})

How can I make that work?

Upvotes: 0

Views: 111

Answers (3)

singpolyma
singpolyma

Reputation: 11241

Create a custom setter method on the Post model, like so:

def tags=(ts)
  ts.each {|tag| self.tags.create(Tag.new(:tag => tag)) }
end

or similar.

Upvotes: 0

Harish Shetty
Harish Shetty

Reputation: 64363

Use the acts-as-taggable-on gem.

class Post < ActiveRecord::Base
  acts_as_taggable_on :tags
end

Post.create(:tag_list => ['tag1', 'tag2'])

Upvotes: 0

Corey
Corey

Reputation: 2243

Might be able to do that with Nested Attributes.

Upvotes: 2

Related Questions