Ruby on Rails, testing for nil in second dimension of the params array
I'm having a bear with some very basic code, which is ...
.form
= semantic_form_for 'thought', :url => thoug开发者_JAVA技巧htstep2_path do |f|
= f.inputs :name => 'Add Something' do
= f.input :title, :hint => "A Hint", :input_html => { :value => params[:thought][:title] }
= f.input :moreinfo, :as => "text", :hint => "Another Hint", :input_html => {:value => params[:thought][:moreinfo]}
= f.buttons
Because the params array I am using to set the :value has a second dimension it bugs out with
You have a nil object when you didn't expect it!
I've tried all sorts of get arounds but to no avail, any ideas anyone?
A few options to try:
{ :value => params[:thought].try(:[], :title) }
{ :value => (params[:thought][:title] rescue nil) }
{ :value => params[:thought] && params[:thought][:title] }
{ :value => (params[:thought][:title] if params[:thought]) }
I'd suggest that you pick the one that you personally find the most readable.
In your helper :
def test(value)
if value
return value;
else
return '';
end
end
In your view :
.form
= semantic_form_for 'thought', :url => thoughtstep2_path do |f|
= f.inputs :name => 'Add Something' do
= f.input :title, :hint => "A Hint", :input_html => { :value => test(params[:thought][:title]) }
= f.input :moreinfo, :as => "text", :hint => "Another Hint", :input_html => {:value => params[:thought][:moreinfo]}
= f.buttons
I'm not sure about this but it's may be a way to fix your problem
精彩评论