ga-wdi-exercises / project2

[project]
1 stars 30 forks source link

jeff session #909

Closed preese13 closed 7 years ago

preese13 commented 7 years ago

I'm attempting to push an array of ID's into sessions to use as a way to enforce a prev/next page.
when this code is run (in my item/show page) it returns the error:

undefined method `name' for ["session_id", "67fa8a3d8289dd185a1eec9c72b1ff53"]:Array

on item.name. I tried to put "before_action :set_session" in my controller, but that gave me an error in a file I have not touched. In the below code, when I switch <%item.id%> to <%=item.id%>, it displays the ID properly, so i know that it is working.

`<%session[:item] = @item.map do |item|%> <%item.id%> <% end %> <% session.each do |item| %>

  • <%= item.name %>
  • <% end %>`

    earlier on the page, I have

    ` <% @item.each do |item| %>

  • <%= item.name %>
  • <% end %>`

    in which item.name functions as desired. I cannot understand what I am doing wrong that Item.name does not work within my session array

    juancgarcia commented 7 years ago

    @preese13 A couple of things:

    The before_action keyword defines a method to be called once before any action in the controller is fired. So to take advantage of before_action :set_session, you need to have a method set_session defined in the same controller:

    def set_session
      # do something to make sure the session is prepared for your other controller actions
      # in your case that might mean to ensure that session[:items] is initialized to an empty array
      # if it doesn't already have an existing array of ids
    end

    Also the mapping (to convert the list of items into a list of ids) and saving that new array to the session should happen in the controller index action, not the view.

    In the index view you have the option of iterating over @items but there's no need to directly touch session in any of the views.

    Try to correct these things first, and then let me know if you have any questions.

    preese13 commented 7 years ago

    that fixed my issue. Thanks.