未定义的方法`each'for#

时间:2014-06-21 22:37:40

标签: ruby-on-rails

Rails 4.1
Ruby 2.0

Credential.rb

class Credential < ActiveRecord::Base
    belongs_to :category
    has_many :user

    validates :name, :login, :password, presence: true

    attr_accessor :encryption_key

    attr_encrypted :login, key: :encryption_key
    attr_encrypted :password, key: :encryption_key
end

User.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :credentials

  def you
    "You are <b>#{email}</b>"
  end
end

CredentialsController.rb

class CredentialsController < ApplicationController
  before_filter :authenticate_user!

  def create
    @credential = current_user.credentials.new
    @credential.encryption_key = session[:master_key]
    @credential.update(credential_params)

    if @credential.save
      redirect_to credential_path(@credential), notice: "Password entry created successfully."
    else
      render "new"
    end
  end

该行:

@credential.update(credential_params)

抛出异常

undefined method 'each' for #<User:0x4de4f58>

1 个答案:

答案 0 :(得分:2)

您需要编辑关联。您的凭据为has_many :user,用户为has_many :credentials。具有外键的那个应该是belongs_to而不是has_many。如果您尝试建立多对多关系,请使用has_many_and_belongs_to或联接表。此外,它应该是has_many :users而不是has_many :user。这应该可以解决你的错误。