Saving a model with a through association

I can’t seem to find any logical way of handling this situation I have
created.

Heres the problem I have worked myself into.

On the create/update of a model, say post, one of the things it has
associated with it is a list of tags. The tags are associated through a
separate model of tags_to_posts. But I wanted to separate the tags by
the word, then save them.

On the PostController.update function i do a split of the tags based on
the spaces. So the submitted params get broken into an array based on
each word. But the save of this always seems to mess up.

This is basically how the situation is set up.

Models:

class Post < ActiveRecord::Base
has_many :tags_to_post
has_many :tags, :through => :tags_to_post
end

class Tag < ActiveRecord::Base
has_many :tags_to_post
has_many :posts, :through => :tags_to_post
end

class Tags_to_post < ActiveRecord::Base
belongs_to :post
belongs_to :tag
end

Edit.html.erb :

Tags <%= text_field_tag 'post[tags]', @post.tags.join(' '), :id => 'post_tags' %>

PostController
def update
@post = Post.find(params[:id])

params[:post][:tags] = params[:post][:tags].split

respond_to do |format|
  if @post.update_attributes(params[:post])
    flash[:notice] = 'Post was successfully updated.'
    format.html { redirect_to(@post) }
    format.xml  { head :ok }
  else
    format.html { render :action => "edit" }
    format.xml  { render :xml => @post.errors, :status =>

:unprocessable_entity }
end
end
end

Anyone have any suggestions for a good way of getting this to work?

Can anyone point me to a good example of how to setup a model with a
has_many :through association?

Any suggestions?

Last bump i guess then i’ll just let it die

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs