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?
You likely need to build the
Barobject under@foo. ieA 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_forin your form,params[:foo]will contain an element calledbar_attributesthat will contain the data entered on the form about the bar object. Look through the railcast I linked to for more info.