jamesdlivesinatree
jamesdlivesinatree

Reputation: 730

Passing an object to a different controller than it's own

I am trying to pass an object to another controller, so that I can sort based on this object. dgroups has_many plans. I am trying to sort my plans based on dgroup.id I have the following code

dgroups view:

    <% @dgroup.each do |dgroup| %>
<tr>
<td><%= dgroup.dings.map(&:id) %></td>
<td><%= dgroup.id %></td>
<td><%= link_to 'Show Plans', plans_path %></td>
<td><%= link_to 'Edit', edit_dgroup_path(dgroup) %></td>
<td><%= link_to 'Destroy', dgroup, method: :delete, data: { confirm: 'Are you sure?' } %></td>

plans controller:

    def index
     @dID = Dgroup.find(params[:id])
     @plans = @dID.plans
    respond_to do |format|
     format.html # index.html.erb
     format.json { render json: @plans }
    end
 end

I've tried passing diaggroup from the dgroups view, like:

<td><%= link_to 'Show Plans', plans_path(dgroup) %></td>

But this did not work. I am not sure why, the errors I was getting made it seem like the controller was assuming I was sending a plan. Any suggestions? I'm really new to ruby so I'm curious how methods on various controllers are supposed to be called. Thanks!

Upvotes: 1

Views: 530

Answers (2)

Victor Moroz
Victor Moroz

Reputation: 9225

Isn't it a good place to use nested resources?

resources :dgroups do
  resources :plans do
  end
end

rake routes
    dgroup_plans GET    /dgroups/:dgroup_id/plans(.:format)          plans#index
...
    dgroup_plan GET    /dgroups/:dgroup_id/plans/:id(.:format)       plans#show

<td><%= link_to 'Show Plans', dgroup_plans(dgroup) %></td>
<td><%= link_to 'Edit Plan', dgroup_plan(dgroup, plan) %></td>

Upvotes: 0

Anezio Campos
Anezio Campos

Reputation: 1555

It seems that what you want is this:

<td><%= link_to 'Show Plans', plans_path(:id => dgroup.id) %></td>

If it doesn't work try to change the parameter name like this:

<td><%= link_to 'Show Plans', plans_path(:dgroup_id => dgroup.id) %></td>

and in your controller:

@dID = Dgroup.find(params[:dgroup_id])

Upvotes: 2

Related Questions