简体   繁体   中英

Rails is not able to grab an object array when I render a controller action

I have 2 controllers:

class SessionsController < ApplicationController

def create
  @person = Person.find_by(email: params[:session][:email].downcase)
  if @person && @person.authenticate(params[:session][:password])
    session[:user_id] = @person.id
    render('people/index')
  else
    render('session/new')
  end
end

class PeopleController < ApplicationController

def index
  @person = Person.all
end

My view is the following:

...

<% @person.each do |p| %>
<tr>
  <td><%= p.name %></td>
  <td><%= p.gender %></td>
  <td><%= p.birthdate %></td>
  <td><%= p.interests_concatenated %></td>
</tr>
<% end %>

When I enter a user's credential and try to login, I get the following error message:

NoMethodError in Sessions#create Showing /Users/fizz/workspace/rails_people/app/views/people/index.html.erb where line #11 raised: undefined method `each' for #Person:0x007fd345aa1778

It looks like Rails is not grabbing the Person.all array and setting it into the @person variable, but why?

The render method just renders a template using the data in the current action. You should use redirect_to instead.

From the Rails layouts and rendering guide:

Another way to handle returning responses to an HTTP request is with redirect_to. As you've seen, render tells Rails which view (or other asset) to use in constructing a response. The redirect_to method does something completely different: it tells the browser to send a new request for a different URL.

You probably want something like this:

def create
  @person = Person.find_by(email: params[:session][:email].downcase)
  if @person && @person.authenticate(params[:session][:password])
    session[:user_id] = @person.id
    redirect_to people_path
  else
    render 'new'
  end
end

Note I also changed it to render 'new' since the controller is sessions not session and you don't even need to specify it in this case.

I would also consider renaming the @person instance variable in the people#index action to @people .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM