How to check if a particular param is sent via submit in Rails
I am working on rails 2.3.11.
I have a doubt in the check_box_tag
<% form_for '', :url => { :action => 'save_subcategories' } do %>
<% for cat in @categories %>
<ul class="checkboxlist" style="display:none;" rel="<%= category.id %>">
<% for category in categories %>
<li>
<%= check_box_tag "#{cat.name}[subcategory_ids][]", subcategory.id,
category.subcategories.include?(subcategory) %><%= subcategory.name.titleize %>
</li>
<% end %>
</ul>
<% end %>
<%= submit_tag "Save Subcategories" %>
For each category I have a list of checkboxes of subcategories which I am trying to save with a single Save button for all.
When I submit the Form - Only those categories where any of their subcategories are checked are alone sent. And it is not sent for other categories whose subcategories which are totally unchecked are not sent via params.
So in my action:
def save_subcategories
categories = Categoryall
for cat in categories
unless params["#{ cat.name }"][:subcat开发者_如何学运维egory_ids].blank?
category_to_edit = role
category.subcategories.clear
subcategories=Subcategories.find(params["#{ cat.name }"][:subcategory_ids])
category_to_edit.subcategories<<subcategories
end
end
redirect_to :action => 'index'
end
The above code throws error as if any of my Category has none of the subcategories checked as it is not sending the category even in params.
To check if a particular parameter is in params you can do:
params.include?(:parameter)
Add this to the first line of your action to see what's getting passed in:
raise params.inspect
In general unchecked checkboxes are not sent (see check_box_tag - one to many relationship), so I suppose, if there's nothing inside the category, it's not sent too.
You could do something like this:
def save_subcategories
categories = Category.all
for cat in categories
from_params = params["#{ cat.name }"]
unless from_params.nil? || from_params[:subcategory_ids].blank?
category_to_edit = role
category.subcategories.clear
subcategories = Subcategories.find(from_params[:subcategory_ids])
category_to_edit.subcategories << subcategories
end
end
redirect_to :action => 'index'
end
I don't know what does it mean in your app when all subcategories are unchecked, but you could clear them all if no checkboxes are passed:
def save_subcategories
categories = Category.all
for cat in categories
from_params = params["#{ cat.name }"]
if from_params && from_params[:subcategory_ids].present?
if from_params[:subcategory_ids].sort != cat.subcategory_ids.sort
category_to_edit = role
category.subcategories.clear
subcategories = Subcategories.find(from_params[:subcategory_ids])
category_to_edit.subcategories << subcategories
end
else
category_to_edit = role # no idea what's that and if it's needed here...
category.subcategories.clear
end
end
redirect_to :action => 'index'
end
精彩评论