Question

I am trying to pass parameters using a generic fields_for method. I have a form:

<%= form_for @Album do |album| %>
...
<%= fields_for :photo do |photo| %>
  <%= photo.text_field :name %>
  <%= photo.text_area  :description %>
  ...
<% end %>
<% end %>

I was hoping this form would generate photo[name] and photo[description] so that when I submit the form, my controller can do a check if params[:photo] exists... #do something. The reason I am not using nested forms, is because sometimes these form fields won't even be used.

The issue is that I am getting is an error for the fields_for :photo line. It says you have a nil object when you didnt expect it! You might have expected an instance of an array.

How can I do this generic fields_for without it being nil?

Was it helpful?

Solution

You're encountering this problem because there's no @photo variable defined in your controller. fields_for, just like form_for, is intended to be a wrapper for an existing object. The symbol :photo is being turned into an instance variable, but it's nil and so that's why you're hitting these errors. You can correct this by defining the photo in the controller action:

@photo = @album.photos.first # if there's an existing photo
@photo = @album.photos.new # if there's not

If you don't want to define an object at all, then you'll need to just use the regular form tags instead of fields_for.

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