0

I have two models, Posts and Hashtags, in a HABTM relationship.

My post controller looks like this:

 def create
    @post = current_user.posts.new(params[:post])

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, :notice => 'Post was successfully created.' }
        format.json { render :json => @post, :status => :created, :location => @post }
      else
        format.html { render :action => "new" }
        format.json { render :json => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

Now, when a user creates a new post, I want to do the following:

  • check for hashtags, words starting with a '#'
  • if the hashtag already exists, link the Post and the Hashtag
  • if the hashtag does not exist, add it to Hashtags, and link the Post and the newly added Hashtag

I suppose I have to do this after I do the posts.new, but I am unsure how to proceed. Do I just edit the @post object? If so, what format should it be in for @post.save to pick up on the link?

Any suggestions would be greatly appreciated!

Doa
  • 1,965
  • 4
  • 19
  • 35

1 Answers1

0

Ok, if you have your relationship setup properly you can run a regex on the post text to get all the hashtags out, then you could assign the hashtags with something like @post.hashtags = tags (tags being the hashtags you extracted from the text) and then save the model.

Another (less proper way I'd say), is to do the same but checking for the existence of the hashtag and creating them and saving them through the model, but good practice dictates that you do this through the relationship with the Post model.

8vius
  • 5,786
  • 14
  • 74
  • 136
  • Ok, tags being what? A list of id's? It's not going to work if tags is simply ['#a','#b']. – Doa Aug 29 '12 at 22:22
  • Rails will save the associations, as in just the content of the hashtags, that's why I also offer the option of saving tag by tag and then linking it to the post. – 8vius Aug 30 '12 at 03:52
  • But will this allow me to do something like showing all posts under the hashtag '#abc'? – Doa Aug 30 '12 at 09:02
  • You will need to add that action in your model and specify how it works yourself, or specify it somehow in the relationship. – 8vius Aug 30 '12 at 15:10