Take the 2-minute tour ×

I have a Member model that belongs to User

class Member < ActiveRecord::Base

    attr_accessible :name
    belongs_to :user


class User < ActiveRecord::Base

    attr_accessible :name
    has_many :members, :dependent => :destroy


In my Members controller I have

class MembersController < ApplicationController

  def create
    @user = User.find(params[:user_id])
    @member  = @user.members.build(params[:member])
    if @member.save
      flash[:success] = "Member created!"
      redirect_to root_path
      render 'pages/home'

In /app/views/users/show.html.erb I have

<%= form_for @member do |f| %>

  <div class="field">
    <%= f.text_area :name %>
  <div class="actions">
    <%= f.submit "Submit" %>
<% end %>

But I get the following error: undefined method `model_name' for NilClass:Class

Extracted source (around line #18):

16: <h1 class="member">What's up?</h1>
18: <%= form_for @member do |f| %>

My show action in the Users controller is

  def show
      @user = User.find(params[:id])
      @members = Member.new
      @title = @user.name

Which also contains the 'new' method

I have tried changing :user_id to :id in the MembersController but this does not work either. What am I doing wrong here?

thanks in advance

share|improve this question
show your SHOW action –  fl00r May 9 '11 at 18:50
Is there a new action defined in the controller? Is your form located at /members/new? –  Fareesh Vijayarangam May 9 '11 at 18:51
The Member.new is defined in the show action in the Users controller. The form is located at app/views/users/show.html.erb thanks –  Zakoff May 9 '11 at 19:20
add comment

2 Answers

Try to replace @members = Member.new by @member = Member.new ;-) !

share|improve this answer
Do I still need the Member.new line if I am using the build method in the Members controller? @member = @user.members.build(params[:member]) –  Zakoff May 9 '11 at 20:38
You must glade at nested model if you want to create members in the user class. weblog.rubyonrails.org/2009/1/26/nested-model-forms –  Hartator May 9 '11 at 21:16
add comment
up vote 0 down vote accepted

I needed to pass the @user.id as a hidden field in the form, for the association to work!

share|improve this answer
add comment

Your Answer


