Controller#create中的NoMethodError

时间:2014-10-15 22:48:09

标签: ruby-on-rails ruby mongodb devise mongoid

我在Ruby-on-Rails和mongoDB上做了一个简单的联系簿API,并且在尝试将联系人分配给用户时遇到了一些问题。

联系模式:

class Contact
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::Attributes::Dynamic

  field :name, type: String
  field :address, type: String
  field :surname, type: String
  field :email, type: String
  field :phone, type: String
  field :birthday, type: Date
  field :notes, type: String

  belongs_to :user
end

用户模型(由设计生成):

class User
  include Mongoid::Document
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  ## Database authenticatable
  field :email,              type: String, default: ""
  field :encrypted_password, type: String, default: ""

   ...

  has_many :contacts, dependent: :destroy
end

从ContactsController创建方法:

def create
    **@contact = @user.contact.new(contact_params)**

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

因此,目的是为当前用户分配联系人,并向当前用户显示他的联系人,不幸的是卡在这个阶段。有什么建议吗?

谢谢:)

1 个答案:

答案 0 :(得分:1)

User中,您有contacts(复数),而不是contact(单数):请参阅has_many :contacts...。这就是@user.contact失败的原因。您应该做的是@user.contacts.build,或contact = Contact.new然后@user.contacts << contact

有关详细信息,请参阅http://guides.rubyonrails.org/association_basics.html#has-many-association-reference