tdahlke
tdahlke

Reputation: 287

Undefined method in devise user model

I'm fairly new to rails and trying to add a belongs_to association to my Devise User model. The error I get when trying to render the view:

NoMethodError in Devise/registrations#edit undefined method `department_id' for #

This error is occurring on the collection_select in my view. Isn't this method provided by the belongs_to association?

User model

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

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me

  belongs_to :department
end

Edit view

%h2
  Edit #{resource_name.to_s.humanize}
= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f|
  = devise_error_messages!
  %p
    = f.label :email
    %br/
    = f.text_field :email
  %p
    = f.label :department
    %br/
    = collection_select(resource_name, :department_id, Department.all, :id, :name)
  %p
    ...

Upvotes: 1

Views: 3537

Answers (4)

Allyl Isocyanate
Allyl Isocyanate

Reputation: 13626

Just to add my case, I had a similar issue. Initially each user had a department with a department_id, then I moved to a has_many, and forgot to remove the department_id from user. Solution was to delete department_id off of user.

Upvotes: 0

naiverahim
naiverahim

Reputation: 21

As mentioned by @njorden, be sure to do the following:

  1. migrate to add department_id to your users table
  2. attr_accessible :department_id to allow mass assignment via edit registration form

Upvotes: 2

njorden
njorden

Reputation: 2606

This really should work, I have a belongs_to :business on my devise User model and an analogous collection_for_select works great. The only thing I can think of is that maybe your migrations haven't run and you don't have the user.department_id column yet?

Upvotes: 0

jdl
jdl

Reputation: 17790

That looks backwards. collection_select would be appropriate for the has_many side of the association. Note that the semantic hint here is that when an object belongs_to another object it's singular. There is no collection involved. You ask for department and get back a one object. From the other direction, if your Department was set to has_many :users then asking for users would give you a list of users.

Take a look at the docs for select. They give a simple example of what you're trying to do with departments (in the form of choosing an author for a blog post).

Upvotes: 0

Related Questions