0

In my application I have List objects and Problem objects, Lists are made up of Problems and problems can belong to many lists. I am using HABTM on both classes and I've created their join table like so:

class AddTableListsProblems < ActiveRecord::Migration
  def up
    create_table :lists_problems, :id => false do |t|
    t.references :list
    t.references :problem
    t.timestamps
end
  end

  def down
    drop_table :lists_problems
  end
end

Now, within the show view of my list I intend to display a list of all Problems and provide a "link_to" to add this problem to the current List being shown but I can't seem to figure out how to. I'm new to RoR so the solution is probably simple though I cant seem to get around it.

This is the code i currently have.

    <% @problems.each do |problem| %>
      <%= render problem %>
          | <%= link_to "Add to current list", <How do I access the List.problems method to add the problem and create a relation?> %>
    <% end %>

Thanks in advance for your help.

2 Answers2

1

Let's say you have a ListController. You'll add an add_problem action to it.

def add_problem
  list    = List.find(params[:id])
  problem = Problem.find(params[:problem_id])

  list.problems << problem # This appends and saves the problem you selected

  redirect_to some_route # change this to whatever route you like
end

And you'll need to create a new route for this. Assuming you're using resourceful routes you might have something like

resources :list do
  member do
    put "add-problem/:problem_id", action: :add_problem, as: :add_problem
  end
end

This will generate the following route

add_problem_list PUT    /list/:id/add-problem/:problem_id(.:format)    list#add_problem

In your view you'll change your link_to

<% @problems.each do |problem| %>
  <%= render problem %>
      | <%= link_to "Add to current list", add_problem_list_path(list: @list, problem_id: problem.id), method: :put %>
<% end %>

Note This is just an example; you'd want to do authorization/validation/etc... in the add_problem method.

deefour
  • 34,974
  • 7
  • 97
  • 90
0

Looking at an example in the rails source, it would appear that you just need to create a new Problem and add that to the List.problems array, then save/update the List.

hd1
  • 33,938
  • 5
  • 80
  • 91