开发者

undefined method `users' for nil:NilClass

开发者 https://www.devze.com 2023-03-29 05:37 出处:网络
I am trying to create an application having domains and users, there are 3 types of users, super admin,domain admins and domain users.All the users(3 types) are in the users table and domains in domai

I am trying to create an application having domains and users, there are 3 types of users, super admin,domain admins and domain users.All the users(3 types) are in the users table and domains in domain table. At present there are domains and super admin. A super admin can login and create domains and domain users. The domains users should be related to a particular domain(i have a "domain_id" column in my 'users' table).Now when i am trying to create a user under a domain(after selecting a domain), i am getting this error "undefined method `users' for nil:NilClass".

My user controller.

def new
    @domain = Domain.find(params[:id])
    @user = User.new
    @title = "Sign up"
end

def create
    @user = @domain.users.build(params[:user])
    if @user.save
       flash[:success] = "Welcome to My Space!"
       redirect_to @user
    else
       @title = "Sign up"
       render 'new'
    end
end

My user model is having.

belongs_to :domain

validates :domain_id, :presence => true

and domain model is having.

has_many :users

My new.html.erb form

<%= form_for @user do |f| %>
  <%= f.label :first_name %>
  <%= f.text_field(:first_name, :size => 20) %>

  <%= f.label :last开发者_Python百科_name %>
  <%= f.text_field(:last_name, :size => 20) %>

  <%= f.label :email %>
  <%= f.text_field(:email, :size => 20) %>

  <%= f.label :password %>
  <%= f.password_field(:password, :size => 20) %>  

  <%= f.label :password_confirmation, "Verify Password" %>
  <%= f.password_field(:password_confirmation, :size => 20) %>

  <%= f.submit "Create" %>

<% end %>


Assuming @domain = Domain.find(params[:id]) in the new method does what it should do:

def new
  @domain = Domain.find(params[:id])
  @user = @domain.users.build
  @title = "Sign up"
end

def create
  @user = User.new(params[:user])
  if @user.save
    flash[:success] = "Welcome to My Space!"
    redirect_to @user
  else
    @title = "Sign up"
    render 'new'
  end
end

And your view should look like this:

<%= form_for @user do |f| %>
  <%= f.hidden_field :domain_id %>

  <%= f.label :first_name %>
  <%= f.text_field(:first_name, :size => 20) %>

  <%= f.label :last_name %>
  <%= f.text_field(:last_name, :size => 20) %>

  <%= f.label :email %>
  <%= f.text_field(:email, :size => 20) %>

  <%= f.label :password %>
  <%= f.password_field(:password, :size => 20) %>  

  <%= f.label :password_confirmation, "Verify Password" %>
  <%= f.password_field(:password_confirmation, :size => 20) %>

  <%= f.submit "Create" %>
<% end %>

Because of the hidden domain_id field in your form, the user will be assigned to the correct domain.

0

精彩评论

暂无评论...
验证码 换一张
取 消