如何使用复选框应用带有acts_as_taggable_on的标签?
我想使用acts_as_taggable_on为公司模型分配两种不同的“类型”标签(扇区类别和免费标记)。 NB:我是RoR的新手!
如果只使用标准文本输入字段,这很容易做,但我想在一种类型(预定义的固定扇区类别标记)上使用复选框,然后允许用户在输入字段中添加逗号分隔标记。
我已经以各种方式解决了这个问题,……一个受这个问题启发的问题 ……但我无法让它发挥作用
这是我到目前为止:
# models/company.rb class Company ... acts_as_taggable_on :tags, :sectors has_many :taggings, :as => :taggable, :include => :tag, :class_name => "ActsAsTaggableOn::Tagging", :conditions => { :taggable_type => "Company" } has_many :sector_tags, :through => :taggings, :source => :tag, :class_name => "ActsAsTaggableOn::Tag", :conditions => {:context => "sectors"} end
在表单中(使用simple_form gem)我有……
# views/companies/_form.html.haml = simple_form_for @company do |f| = f.input :name = f.association :sector_tags, :as => :check_boxes, :hint => "Please click all that apply" = f.input :tag_list = f.button :submit, "Add company"
在我的公司控制器中我有
# controllers/companies_controller.rb def create @company = current_user.companies.build(params[:company]) if @company.save ... end
但这会导致validation错误:
ActiveRecord::RecordInvalid in CompaniesController#create Validation failed: Context can't be blank
任何人都可以暗示我能做到这一点吗?
一个相关的问题是,这是否是一个很好的方法呢? 使用Category模型通过联合模型分配扇区标签会更好吗?
谢谢!
好吧,我解决了我的问题。 事实certificate这很简单。 唉,我最终通过联合“sectorizations”表创建了一个单独的Sector模型。 但如果有人感兴趣,我只是想更新我在上面的案例中所做的事情……
在我的公司模型中
# models/company.rb class Company ... acts_as_taggable_on :tags, :sectors ... end
在表格中
# views/companies/_form.html.haml = simple_form_for @company do |f| = f.input :name = f.input :sector_list, :as => :check_boxes, :collection => @sectors, :hint => "Please check all that apply" = f.input :tag_list = f.button :submit, "Add company"
并在公司控制器(创建)
# controllers/company_controllers.rb def new @company = Company.new @sectors = get_sectors end def get_sectors sectors = [] for sector in Company.sector_counts sectors << sector['name'] end return sectors end
似乎act_as_taggable_on使用单表inheritance,因此您实际上不需要创建任何其他表。 但是你需要按照他们的约定(他们从未说过)如下:
//add to model attr_accessible :yourfieldname_list acts_as_taggable_on :yourfieldname //view <%= f.text_field :yourfieldname_list %>