【问题标题】:Rails 5 - First argument in form cannot contain nil or be emptyRails 5 - 表单中的第一个参数不能包含 nil 或为空
【发布时间】:2017-03-06 10:35:08
【问题描述】:

我正在尝试为 编辑视图 创建一个表单,但我得到“表单中的第一个参数不能包含 nil 或为空”。

我有一个类似的新视图表单,适用于:

<%= form_for(@user, url: signup_path) do |f| %>

我想为编辑和新建使用共享表单,但我无法检索@user 以使其工作。感谢您的帮助!

views/user/edit.html.erb >

  <%= form_for(@user) do |f| %>
    <%= render 'shared/error_messages' %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <%= f.label :email %>
    <%= f.email_field :email, class: 'form-control' %>

    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

      <%= f.label :password_confirmation, "Confirmation" %>
      <%= f.password_field :password_confirmation, class: 'form-control' %>

    <%= f.submit "Save changes", class: "btn btn-primary" %>
  <% end %>

users_controller.rb >

def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      flash.now[:danger] = 'There was an error updating your account, try again'
      render 'edit'
    end
  end

routes.rb >

Rails.application.routes.draw do
  root 'static_pages#home'
  get  '/about',   to: 'static_pages#about'
  get  '/contact', to: 'static_pages#contact'
  get  '/signup',  to: 'users#new'
  post '/signup',  to: 'users#create'
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'
  resources :users
end

【问题讨论】:

    标签: ruby-on-rails ruby forms ruby-on-rails-5


    【解决方案1】:

    表单在edit 操作上,而不是update

    因此,您需要添加edit 操作,从中获取@user 实例变量:

    def edit
      @user = User.find(params[:id])
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多