Reputation: 1549
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.
Upvotes: 5
Views: 9797
Reputation: 561
After researching this myself, you should be able to do
def add_post
j = Journal.first # or find_by, etc
p = Post.first # or find_by, etc
j.posts << p # creates a record in journals_posts table
j.save!
end
(1) The accepted answer made it sound as though the association could only be made directly. Also you wouldn't have a "JournalsPosts" class if you're using the habtm association, since it specifically avoids using a model for the intermediary table.
(2) Note that this association will not be unique. If you call this multiple times, you'll get multiple entries in the journals_posts table with the same two integer pairs.
Upvotes: 16
Reputation: 2266
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
Upvotes: -3