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.
You should highly consider using
has_many, :throughas 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:
In your view (make sure you set
@journaland@postsomewhere):<%= link_to "Add to Journal", add_post_journal_path(@journal, :post_id => @post.id), :method => :put %>In your controller: