0

这是我未更改的控制器:

  def create
    @user = User.new(params[:user])

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

这是我的路线:

  root :to => "songs#index"
  match '/votes/:song_id/:user_id' => "votes#create"
  resources :votes

  resource :session

  resources :users

  resources :songs

  match '/login' => "sessions#new", :as => "login" 
  match '/logout' => "sessions#destroy", :as => "logout" 

和错误:

undefined method `user' for #<User:0x00000102b42a00>


Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:46:in `block in create'
app/controllers/users_controller.rb:45:in `create'
Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"oOzmpsbEJtnHC4YGeAf4N6pVxfK+Zf4W9ec+0E/Eds0=",
 "user"=>{"email"=>"bhjjhb@hui.com",
 "password"=>"[FILTERED]"},
 "commit"=>"Create User"}

模型:

class User < ActiveRecord::Base
  attr_accessible :email, :password
  validates_uniqueness_of :user
  validates_presence_of :password

  has_many :votes


end
4

2 回答 2

2

http://guides.rubyonrails.org/active_record_validations_callbacks.html#uniqueness

这个助手验证属性的值是唯一的

您的问题在于您的验证;validates_uniqueness_of检查模型属性的唯一性,因此validates_uniqueness_of :user尝试检查用户的user属性是否唯一。在此过程中,它调用@user.user,从而生成NoMethodError.

编辑添加:正如@Amar 所说,解决此问题的方法是验证某些属性或属性集的唯一性,这些属性或属性集对于每个用户记录都是唯一的(例如:email)。

于 2012-09-11T13:22:28.090 回答
1

而不是validates_uniqueness_of :user使用此validates_uniqueness_of :email 验证主要适用于属性

于 2012-09-11T13:29:05.213 回答