Simple non-model check box properties

March 6, 2009

 
No Gravatar

Need to pass a property that isn’t associated with a model? I did. It took me a few minutes, but the solution is pretty easy.

Instead of passing the instance variable your form is using, try this.

<% form_for [:admin, @post]} do |f| %>
  <%= f.error_messages %>
 
	<p>
		<%= f.label :title %>
		<%= f.text_field :title %>
	</p>
 
	<p>
		<%= label(:skip_queue, "Skip queue") %>	
		<%= check_box("overrides", "skip_queue") %>	
	</p>
 
	<p>
		<%= f.submit "Submit" %>
	</p>
<% end %>

You’d access the property of the check box like so:

# log
Processing Admin::PostsController#create (for 127.0.0.1 at 2009-03-06 03:03:01) [POST]
  Parameters: {"commit"=>"Update", "post"=>{"title"=>"Title", "overrides"=>{"skip_queue"=>"1"}}
 
# access the property
params[:overrides][:skip_queue]
  • Hey nice blog. I have one similiar. Would you be interested in exchanging blogroll links?
  • bdeank
    It's easy to forget that you can use the stand-alone FormHelper methods when you are in model/attribute mode. Thanks for this. I just have one possibility to add:

    If you aren't using other 'overrides', you may as well use check_box_tag. This would clean up your code and give you extra flexibility when setting the check box initial value.

    # View
    <% form_for [:admin, @post] do |f| %>
    ...


    <%= label_tag(:skip_queue, 'Skip queue') %>
    <%= check_box_tag(:skip_queue) %>


    ...
    <% end %>

    # Controller
    # access the property
    params[:skip_queue]
blog comments powered by Disqus