Rails:选择要关联的多个标记对象

时间:2013-10-25 00:53:57

标签: ruby-on-rails ruby-on-rails-3 forms

所以我正在开发一个项目,我有一个文档对象(基本上是一个E-Library应用程序),我有一堆Tag对象,我希望能够与它关联。目前我在两者之间有一个has_and_belongs_to_many关联。我的问题是标签的形式,从可用标签列表中选择与该文档关联的最佳方法是什么?我是否必须在控制器中做任何奇特的工作来实现这一目标?

我正在使用rails 3.2

以下是一些代码:

# This is the text model
# It will not have an attachment but instead it's children will
class Text < ActiveRecord::Base
  attr_accessible :name, :author, :date, :text_langs_attributes, :notes
  has_many :text_langs, dependent: :destroy
  belongs_to :item
  validates :author, presence: true
  has_and_belongs_to_many :tags
  accepts_nested_attributes_for :text_langs

    def get_translations
        TextLang.where(:text_id => self.id)
    end

    def get_language(lang)
        TextLang.where(:text_id => self.id, :lang => lang).first
    end
end

这是标签:

# This is the Tags class
# It has and belongs to all of the other file classes
# the tags will need to be translated into four langauges
# Tags will also own themselvea
class Tag < ActiveRecord::Base
  attr_accessible :creole, :english, :french, :spanish, :cat,
      :english_description, :french_description, :spanish_description,
      :creole_description, :parent_id
  has_and_belongs_to_many  :texts
  has_and_belongs_to_many  :sounds
  belongs_to :parent, :class_name => 'Tag'
  has_many :children, :class_name => 'Tag', :foreign_key => 'parent_id'
  validates :cat, presence: true, inclusion: { in: %w(main sub misc),
    message: "%{value} is not a valid type of tag" }
  validates :english, :spanish, :french, :creole, presence: true

  TYPES = ["main", "sub", "misc"]
end

这是表格:

= form_for @text do |f|
  - if @text.errors.any?
    #error_explanation
      %h2= "#{pluralize(@text.errors.count, "error")} prohibited this text from being saved:"
      %ul
        - @text.errors.full_messages.each do |msg|
          %li= msg

  .field
    = f.label :name
    = f.text_field :name

  .field
    = f.label :date
    = f.date_select :date

  .field
    = f.label :author
    = f.text_field :author

  = f.fields_for :text_langs do |pl|
    .field
      = pl.label :title
      = pl.text_field :title
    .field
      = pl.label :lang
      = pl.text_field :lang
    .field
      = pl.label :description
      = pl.text_field :description, :size => 150
    .field
      = pl.label :plain_text
      = pl.text_area :plain_text
    .field
      = pl.label :published
      = pl.check_box :published
    .field
    = f.label :txt
    = f.file_field :txt


  .field
    = f.label :notes
    = f.text_area :notes, :rows => 10



  .actions
    = f.submit 'Save'

1 个答案:

答案 0 :(得分:1)

首先,我建议尝试simple_form gem它会让你的表格变得简单干净。它们具有非常好的关联功能。

你会结束这样的事情:

= simple_form_for @text do |f|
  ...
  = f.association :tags,   as: :check_boxes

可以是复选框,单选按钮,也可以是需要多个值的选项。

希望有所帮助