2014-10-15 4 views
0

Я делаю простой API-интерфейс контактов на Ruby-on-Rails и mongoDB и сталкиваюсь с некоторыми проблемами, пытаясь назначить контакты пользователю.NoMethodError in Controller # create

Контактная модель:

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

В 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.