未定义的方法`model_name'对于NilClass:Class

时间:2013-10-20 16:49:44

标签: ruby-on-rails devise

我在Rails 3.2中遇到设计错误 - 我的观点是在下面的第1行(用户)上说未定义的方法。此视图是登录用户的编辑个人资料页面。

到目前为止,我已经尝试将其更改为current_user并在我在下面提供的控制器中定义,但这不起作用。

我唯一的另一个怀疑是form_for不适合在这个页面上使用?

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :username %><br>
    <%= f.text_field :username %>
  </div>
  <div class="field">
    <%= f.label :firstname %><br>
    <%= f.text_field :firstname %>
  </div>
  <div class="field">
    <%= f.label :lastname %><br>
    <%= f.text_field :lastname %>

我的控制器......(正如我所说,我试过current_user)

class UsersController < ApplicationController

  def current_user
    @current_user ||= User.find(session[:user_id])
  end

  def find
    @user = User.new
  end

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

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render action: 'show', status: :created, location: @user }
      else
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:username, :firstname, :dateofbirth, :lastname, :gender, :location, :email, :password)
    end


end

1 个答案:

答案 0 :(得分:0)

Devise附带了current_user辅助方法。您可能不想覆盖它,因此我建议您从控制器中删除该方法。在我的某个应用中,我允许用户编辑他们的信息,这是我的edit方法:

def edit
  @user = current_user
end