Frank Jensen
Frank Jensen

Reputation: 367

Creating new blog with tags

Im trying to setup a blog with tagging, and i've run into a problem when trying to save.

I got 3 models

blog model

has_many :blog_tags
has_many :tags, :through => :blog_tags

blog_tag model

belongs_to :blog
belongs_to :tag

tag model

[nothing]

When i post my blog form, i got an input field with a comma seperated list of tags that i would like to create in the blog_tags tabel.

I've been trying out some different stuff and ended up with this

@blog_tags = params[:blog][:tags].split(",")

@blog_tags.each do |tag|
  @tag = Tag.find_by_tag(tag)
  @blog.tags.push(@tag)
end

Seemed to be working besides it complained that the parent wasn't created, and in the 2nd try it gave me an error for trying to split the string "string1" which i guess is caused by not having any commas.

I really hope one of you out there can help me out here, or atleast point me in the right direction :-)

Thanks!

Upvotes: 1

Views: 477

Answers (2)

ankit
ankit

Reputation: 3358

I think you just need to handle the cases where params[:blog][:tags] has no commas. In this case, the whole string is one tag, so just add it.

You might also need to deal with cases like "ruby, ,rails" i.e making sure the tags aren't empty.

Upvotes: 0

lucapette
lucapette

Reputation: 20724

I'd go for a gem. Try https://github.com/mbleigh/acts-as-taggable-on for example.

Upvotes: 1

Related Questions