Ossie
Ossie

Reputation: 1113

Delete a join table entry from associated model

I'm trying to setup a delete link for a join table entry.

I have a @miniatures model which has_many @lines through the @minilines join table.

On my @miniatures show page I call the associated @lines with

<% @miniature.lines.each do |line| %> 
    <%= link_to line.name, line %>
<% end %>

That all works fine. All associations correct etc. What I'm trying to do is add a little delete link. It's currently as follows

<% @miniature.lines.each do |line| %> 
    <%= link_to line.name, line %>
  <%= link_to '<i class="fa fa-times"></i>'.html_safe, miniline_path(:miniature_id => @miniature.id, :line_id => line.id),
            :confirm => 'Are you sure?', :method => :delete %><br />
<% end %>

In my mini lines_controller I have the following destroy action

def destroy
    Miniline.find_by_miniature_id_and_line_id(params[:miniature_id, :line_id]).destroy
    flash[:success] = "Miniature removed from product line."
    redirect_to :back
end

It's currently returning wrong number of arguments (2 for 1).

Upvotes: 0

Views: 281

Answers (2)

leesungchul
leesungchul

Reputation: 111

If you have your routes and controllers setup correctly, you can type rake routes in terminal and check out the delete path for minilines. You can send the miniature and line model with the path. Then in the controller, instead of finding by id. you can do something like this MiniLine.find_by_miniature_id_and_line_id(miniature.id, line.id), then destroy the result.

Upvotes: 1

Anil Maurya
Anil Maurya

Reputation: 2328

you can use nested form for this .

<%= f.fields_for :lines, :wrapper => false do |task_form| %>
    <tr class="fields">
      <td><%= task_form.text_field :name %></td>
      <td><%= task_form.link_to_remove "Remove this line" %></td>
    </tr>
  <% end %>

Upvotes: 0

Related Questions