ruby-on-rails – 如何使用复选框应用带有acts_as_taggable_on的标签?

我想使用 acts_as_taggable_on为公司模型分配两种不同的“类型”标签(扇区类别和免费标签).注意:我是RoR的新手!

如果只使用标准文本输入字段,这很容易做,但我想在一种类型(预定义的固定扇区类别标记)上使用复选框,然后允许用户在输入字段中添加逗号分隔标记.

我以各种方式解决了这个问题,…一个受到this question启发的……但我无法让它发挥作用

这是我到目前为止:

# 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

但这会导致验证错误

ActiveRecord::RecordInvalid in CompaniesController#create
Validation Failed: Context can't be blank

任何人都可以暗示我能做到这一点吗?

一个相关的问题是,这是一个很好的方法吗?如果仅使用Category模型通过联合模型分配扇区标签,我会更好吗?

谢谢!

解决方法

好吧,我解决了我的问题.事实证明这很简单.唉,我最终通过联合“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,: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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...