开发者

nil object error when a form in a partial is submitted

Rails 2.3.5

I have a problem where a form select is working properly except when the form is submitted I get a nil error against the array being used. I'm not understanding how the Select tag is working and generating the correct HTML but also giving a nil error against the array when the form is submitted. Also, if I take the logic out of the controller and stick it directly in the partial, it works fine. Thanks for any help.

In a controller I have this code in a "new" method:

@directories = Directory.find(:all, :conditions => {:id => session[:directories_with_view_access]})
@directories.collect! {|u| [u.name, u.id]}

Inside a partial for the "new" view, I have this code:

<%= f.select(:directory_id, @directories, :prompt => 'Select') %>

Which renders this HTML:

<select id="card_directory_id" name="contact[directory_id]"><option value="">Select</option>
<option value="2">dir_test_1</option>
<option value="4">dir_test_2</option>
<option value="6">dir_test_3</option>

The problem is, when I submit the form, I get the following error:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.inject

If I take the logic out of the controller and put it into the partial, everything works fine:

<%开发者_开发知识库= f.select(:directory_id, Directory.find(:all, :conditions => {:id => session[:directories_with_view_access]}).collect {|u| [u.name, u.id]}, :prompt => 'Select') %>


Your use of the select tag is not the issue here.

I would be able to diagnose your problem better if you posted a stack trace, but from what you've described, my guess is that your form submits a post request to an action such as create, that in turn redirects to a page that is rendering the form partial again. @directories is not getting set in the redirected action that is responsible for rendering the view as it was set in the new action.

Look in your create action for a redirect url, then make sure @directories is set in that action (quite possibly the show action, as in redirect_to url_for(@object)), just as it is in your new action.

The key thing to understand here is what controller action is actually handling your POST request, what action is rendering your view, and making sure that the necessary variables get defined there. Reading up on RESTful routes is essential if you're using traditional Rails architecture, such as gets built for you by the scripts in script/generate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜