Question

I have a couple of objects, foo, bar and user.

I have a form for creating a new foo object, which uses simple_fields_for and accepts_nested_attributes_for to create a new child bar object at the same time.

Now, I want to set the current_user as the author attribute for the new bar, but I can't figure out how best to do this. (still new to Rails.)

I have tried the following in my create method within the foo controller:

def create
    @foo = Foo.build(params[:foo])

    @foo.bars.find(:first).author = current_user

However when I run this I get an exception.

undefined method `author=' for nil:NilClass

Can anyone offer any advice on how best to go about this?

Was it helpful?

Solution

You likely need to build the Bar object under @foo. ie

def new
  @foo = Foo.new
  @foo.bars.build
end

def create
   @foo = Foo.new(params[:foo])
   @foo.bars.first.author = current_user
   if @foo.save 
     redirect_to @foo
   else
     render action: "new"
   end
end

A good resource for nested forms: http://railscasts.com/episodes/196-nested-model-form-part-1?view=asciicast

Provided you set accepts_nested_attributes_for in your model and correctly used fields_for in your form, params[:foo] will contain an element called bar_attributes that will contain the data entered on the form about the bar object. Look through the railcast I linked to for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top