Module: ActionController::Macros::ManyToMany::ClassMethods
- Defined in:
- lib/smklib/htmlutils.rb
Overview
Example:
# Controller
class BusinessesController < ApplicationController
many_to_many_for :business, :subcategories, :label => _('Subcategory'), :m2m_field_options => {:item_name => 'name_with_category'}
end
# View
xml.div(:id => 'm2m_business_subcategories') do
many_to_many_field(xml, 'business', 'subcategories', _('Subcategory'), @subcategories, :item_name => 'name_with_category')
end
Instance Method Summary collapse
Instance Method Details
#many_to_many_for(object, attribute, options = {}) ⇒ Object
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 |
# File 'lib/smklib/htmlutils.rb', line 565 def many_to_many_for(object, attribute, = {}) #include SMKLib::HtmlUtils = {:max_size => 10, :label => attribute.to_s.capitalize}.merge() parent_model, child_model = object.to_s.camelize.constantize, attribute.to_s.singularize.camelize.constantize @controller = self define_method("add_#{attribute.to_s.singularize}_to_#{object}") do instance_variable_set("@#{object}", parent_model.find(params[:business_id])) collection = instance_variable_get("@#{object}").send(attribute.to_s) if collection.size >= [:max_size] flash[:alert] = _("Can't add. This %s already has %d %s.") % [object, [:max_size], attribute] else if params[:subcategory_id].to_i > 0 collection << child_model.find(params[:subcategory_id]) rescue flash[:alert] = _('%s already linked to this %s.') % [attribute.to_s.capitalize.singularize, object] else c = Category.find_or_create_by_name(params[:categories]) collection << child_model.find_or_create_by_name_and_category_id(params[:subcategory_id], c[:id]) end end redirect_to :action => 'edit', :id => instance_variable_get("@#{object}")[:id] # many_to_many_field(nil, object, attribute, options[:label], child_model.find_all, options[:m2m_field_options].merge(:controller => self)) end define_method("remove_#{attribute.to_s.singularize}_from_#{object}") do instance_variable_set("@#{object}", parent_model.find(params[:business_id])) instance_variable_get("@#{object}").send(attribute).delete(child_model.find(params[:subcategory_id])) redirect_to :action => 'edit', :id => instance_variable_get("@#{object}")[:id] #raise many_to_many_field(nil, object, attribute, options[:label], child_model.find_all, options[:m2m_field_options].merge(:controller => self)) end end |