Rails: первый аргумент в форме не может содержать ноль или быть пустым - PullRequest
0 голосов
/ 09 октября 2018

Есть у меня файл контроллера белов.Как видите, я определил методы создания, индексации, показа и редактирования.

    class PeopleController < ApplicationController

before_action :authenticate_user!
#before_action :people_params
before_action :exist_or_not, except:[:show, :index, :edit]


  def new
    @person = Person.new
  end

  def show
    @person = Person.find_by(id: params[:id])
  end

  def index

  end

  def edit
  @person = Person.find_by(id: params[:id])

  end


def update
  @person = Person.find_by_id(params[:id])
   if @person.update_attributes(people_params)
    flash[:success] = 'person was updated!'
    redirect_to person_edit_path
    else
    render 'edit'
    end
  end

 def create

 if Person.exists?(user_id: current_user.id)
        flash[:warning] = 'you have already details!'
      redirect_to root_path

 else
   @person = current_user.build_person(people_params)
    if @person.save
      flash[:success] = 'person was created!'
      redirect_to root_path
    else
      render 'new'
    end
 end


  end





private

def people_params
    params.require(:person).permit(:gender, :birthday, :country_id,:country_name,:state_id, :lang, :id, :user_id)

end


def exist_or_not

    if Person.exists?(user_id: current_user.id)
        flash[:warning] = 'you have already details!'
      redirect_to root_path

    end
end

end

Также я поделился своим файлом _form.html.erb Белов.

<%= form_for @person do |f| %>


  <div class="field">
    <%= f.label :birthday %><br />
    <%= f.date_select :birthday, :start_year=>1950, :end_year=>2005 %>
  </div>

    <div class="field">
   <%= f.radio_button(:gender, "male") %>
<%= f.label(:gender_male,   "Male") %>
<%= f.radio_button(:gender, "female") %>
<%= f.label(:gender_female, "Female") %>
  </div>

  <div class="field">
    <%= f.label :country_id %><br />
    <%= f.collection_select :country_id, Country.order(:name), :id, :name, include_blank: true %>
  </div>



  <div class="field">
    <%= f.label :state_id, "State or Province" %><br />
    <%= f.grouped_collection_select :state_id, Country.order(:name), :states, :name, :id, :name, include_blank: true %>
  </div>

<%= f.select :lang, collection: LanguageArray::AVAILABLE_LANGUAGES.sort.map {|k,v| [v,k]} %>


  <div class="actions"><%= f.submit %></div>
<% end %>

Проблема в том, что я могу создавать и показывать людей, но редактировать.Я не могу открыть путь редактирования или страницу.

"Первый аргумент в форме не может содержать ноль или быть пустым"

Снимок вывода ошибки: Нажмите для вывода ошибки для браузера

Пожалуйста, помогите мне об этой ошибке.Спасибо.

1 Ответ

0 голосов
/ 09 октября 2018

find_by возвращает nil, когда ничего не найдено, поэтому @person равно nil, таким образом, эта ошибка.

Для действий над объектом, таких как show / edit / update / etc.Лучше использовать Person.find(params[:id]), это повысит ActiveRecord::RecordNotFound, когда объект не найден (позже он будет обработан как ошибка http 404).

Что касается того, почему нет объекта - проверьте, правильно ли сгенерирован URLи params[:id] содержит соответствующий идентификатор (например, вы можете передать идентификатор другого объекта в urlhelper, что приведет к правильно выглядящему URL, который ни к чему не приведет).

Также, возможно, вы пропускаете параметр для person_edit_path

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...