Reputation: 293
I have a page called lastthree.html.erb
that is displaying data for the Ownerships model. I have a partial called _nextpick.html.erb
, also for Ownerships model.
In my ownerships_controller.rb
, I have two definitions:
def nextpick
@ownerships = Ownership.take(Rails.application.config.counter).last(1)
end
def lastthree
@ownerships = Ownership.take(Rails.application.config.counter - 1).last(3)
end
If I make nextpick
its own page (nextpick.html.erb
) and access it from the menu, it works fine and I get the correct result. But if I render it as a partial from lastthree.html.erb
, I get the results of the lastthree
query. Its doesn't matter where I render it on the page.
Why is the nextpick
query being ignored? Is there anyway to overcome this?
Both pages use the same code to display the data:
<% @ownerships.each do |ownership| %>
<tr>
<td></td>
<td><%= ownership.round %></td>
<td><%= ownership.pick %></td>
<td><%= image_tag ownership.team.logo.url(:medium) %></td>
<td><%= ownership.team.name %></td>
<% if ownership.player_id == nil %>
<% else %>
<td><%= ownership.player.name %></td>
<% end %>
</tr>
<% end %>
Upvotes: 0
Views: 392
Reputation: 601
If I understood correctly. Your problem is that you are expecting your two controller methods get called but it doesn't work that way.
When you visit a url, rails knows what controller and what controller action to call based on your routes.rb file configuration.
Since you are accessing the lastthree url (which I think should be named last_three if you are following conventions) your path might look like /lastthree. Based on the behavior you described I guess you have something like this in your routes.rb file
get '/lastthree', to: 'ownerships#lastthree'
get '/nextpick', to: 'ownerships#nextpick'
A request will always map to one controller action. The fact that you render your nextpick partial in the lastthree view doesn't mean that the nextpick method is being called at all. Controller methods are called based on the requested route not based on the rendering of the views.
To answer your question: yes, you can have both results. But for that you would need to either add a before_action or after_action callback in your controller to call the nextpick method or to call that method directly from your lastthree method. Also, you will need give the instance variables different names or else the method that gets called last will end up overriding the variable and you will end up in the same situation.
You might consider passing the variables as locals to your views in order to avoid your views depending on too many instance variables. As a good practice you should try only use one instance variable per view.
Upvotes: 1