I have two Model/Controllers which are essentially duplicating data (just on different pages). When I iterate through a collection on one of the controllers, it works just as intended, however when I run the collection through the partial on the other controller, it creates another “object”
def show (users_controller.rb)
...
@missions = @user.missions
@mission = current_user.missions.build
...
end
def index (missions_controller.rb)
...
@missions = @user.missions
@mission = current_user.missions.build
...
end
When I call render @missions (app/views/missions/_mission.html.erb) on both the show.html.erb and index.html.erb files. It works as intended on the Users_controller but creates an extra “object” on the Missions_controller. It seems to be rendering both the @mission and @missions variables in the controller when rendering the collection.
Why and how can I fix this? I’ve tried moving the partial to a shared view directory, but the problem remains. I’m assuming it has to do with how I named my instance variables? I’m super stumped. Thanks guys
This is just a guess, but I would say this is likely happening because the mission you’re building is included in @user.missions. Criteria aren’t evaluated until they’re actually used (by calling .all or .each or something) so by using current_user.missions.build you’re adding an empty mission to the end of @user.missions… assuming that current_user and @user are the same.
So you can probably fix this by changing the call to
@missions = @user.missions.allwhich will force it to be evaluated immediately, before the built mission is added to the end.As I said, just a guess though!