ruby on rails - NoMethodError in Controller#create -
i'm doing simple contact-book api on ruby-on-rails , mongodb , facing problems trying assign contacts user.
contact model:
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
user model (generated devise):
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
and create method contactscontroller:
def create **@contact = @user.contact.new(contact_params)** respond_to |format| if @contact.save format.html { redirect_to @contact, notice: 'contact 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
so, aim assign contact current user , show current user contacts, unfortunately stuck on phase. suggestions?
thanks :)
in user
have contacts
(plural), not contact
(singular): see has_many :contacts...
. that's why @user.contact
fails. should have done @user.contacts.build
, or contact = contact.new
, @user.contacts << contact
.
see http://guides.rubyonrails.org/association_basics.html#has-many-association-reference more details.
ruby-on-rails ruby mongodb devise mongoid
No comments:
Post a Comment