gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:35:02 29 4
gpt4 key购买 nike

我想使用 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"

在我的公司 Controller 中,我有
# 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

谁能暗示我如何正确地做到这一点?

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

谢谢!

最佳答案

嗯,我解决了我的问题。结果证明这很简单。唉,我最终通过联合“部门化”表创建了一个单独的部门模型。但是,如果有人感兴趣,我只想更新我在上述案例中所做的事情......

在我的公司模型中

# 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"

并在公司 Controller 中(创建)
# 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

关于ruby-on-rails - 如何使用复选框应用带有acts_as_taggable_on 的标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4469143/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com