Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-3.2

How create record in HABTM Rails Association How make this?


I'm having some trouble creating a new relation in my has_and_belongs_to_many model. I defined the models like this:

journals model

  has_and_belongs_to_many :posts

post model

  has_and_belongs_to_many :journal

I don't know how create the association , I made a button but I don't know how it works. I created the action add_post

  def add_post
    @journal_post = JournalsPosts.new
  end

I make this link to create the association but I don't know what I have to do now:

<%= link_to "Add to Journal",:controller => "journals",:action => "add_post" %>

The redirect works correctly but I don't know how to proceed now ? Do you know about some guide to HABTM associations? I have already tried this, but it didn't help.


Solution

  • You should highly consider using has_many, :through as that's the preferred way to do these kinds of relationships now in Rails.

    That said, if you want to continue with has_and_belongs_to_many, you need to somehow get the journal and post ids that you want to associate so you can correctly create the association.

    In your routes:

    resources :journals do
      member do
        put :add_post
      end
    end
    

    In your view (make sure you set @journal and @post somewhere):

    <%= link_to "Add to Journal", add_post_journal_path(@journal, :post_id => @post.id), :method => :put %>

    In your controller:

    def add_post
      @journals_posts = JournalsPosts.new(:journal_id => params[:id], :post_id => params[:post_id])
    
      if @journals_posts.save
        ...
      else
        ...
      end
    end