Rails association - difficulty getting form_for to work
I have a Member model that belongs to User
class Member < ActiveRecord::Base
attr_accessible :name
belongs_to :user
end
class User < ActiveRecord::Base
attr_accessible :name
has_many :members, :dependent => :destroy
end
In my Members controller I have
class MembersController < ApplicationController
def create
@user = User.find(params[:user_id])
@member = @user.members.开发者_Python百科build(params[:member])
if @member.save
flash[:success] = "Member created!"
redirect_to root_path
else
render 'pages/home'
end
end
end
In /app/views/users/show.html.erb I have
<%= form_for @member do |f| %>
<div class="field">
<%= f.text_area :name %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
But I get the following error: undefined method `model_name' for NilClass:Class
Extracted source (around line #18):
15:
16: <h1 class="member">What's up?</h1>
17:
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
end
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
Try to replace @members = Member.new
by @member = Member.new
;-) !
I needed to pass the @user.id as a hidden field in the form, for the association to work!
精彩评论