small medium large xlarge

Generic-user-small
26 Jun 2008, 00:23
Jeffrey Lee (3 posts)

I’m trying to save a username along with profiles (User has_many Profiles; Profile belongs_to User). I had a portion of this working (updating user info) but I cannot create new user records. I get the following error:

You have a nil object when you didn’t expect it! The error occurred while evaluating nil.build

Parameters:

{"commit"=>"Create record",
 "profile"=>{"company"=>"",
 "new_user_attributes"=>[{"username"=>"jlee",
 "active"=>"1"}],
 "new_someid_attributes"=>[{"someid"=>"123456789"}],
 "type_id"=>"2",
 "first_name"=>"Jeffrey",
 "last_name"=>"Lee"},
 "authenticity_token"=>"65507986d1912380edf522b5b9f7ee3763c6dc0d"}

I am getting stuck on the profile model code below:

	# Users
	def new_user_attributes=(user_attributes)
		user_attributes.each do |attributes|
			user.build(attributes)
		end
	end
	def existing_user_attributes=(user_attributes)
		user.reject(&:new_record?).each do |user|
			attributes = user_attributes[user.id.to_s]
			if attribute
				user.attributes = attributes
			else
				user.delete(email)
			end
		end
	end
	def save_user
		user.save(false)
	end

New method in profiles_controller:

  def new
    @profile = Profile.new
    @profile.user = User.new
  end

User partial:

<div class="user">
	<% new_or_existing = user.new_record? ? 'new' : 'existing' %>
	<% prefix = "profile[#{new_or_existing}_user_attributes][]" %>
	<% fields_for prefix, user do |user_form| -%>
		<%= label :user_form, :user, "Username" %><%= user_form.text_field :username %>
		<%= user_form.hidden_field :active, :value => "1" %>
	<% end -%>
</div>
You must be logged in to comment