0

所以我正在做一个项目,我有一个文档对象(基本上是一个电子图书馆应用程序),我有一堆我希望能够与之关联的标签对象。目前,我在has_and_belongs_to_many两者之间建立了联系。我的问题是标签的形式,从可用标签列表中选择与该文档关联的最佳方法是什么?我是否必须在控制器中做任何花哨的工作才能做到这一点?

我正在使用导轨 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'
4

1 回答 1

1

首先,我建议尝试simple_form gem,它会使您的表单干燥且简单。它们具有非常好的关联功能。

你会结束做这样的事情:

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

如果需要,可以是复选框、单选按钮或具有多个值的选择。

希望能帮助到你

于 2013-10-25T04:36:38.703 回答