0

そのため、ドキュメント オブジェクト (基本的には E-Library アプリケーション) があり、それに関連付けたいタグ オブジェクトがたくさんあるプロジェクトに取り組んでいます。現在、私はhas_and_belongs_to_many2つの間の関連付けを持っています。私の質問はタグのフォームにあります。使用可能なタグのリストから選択してそのドキュメントに関連付ける最良の方法は何ですか? そして、これを実現するために、コントローラーで特別な作業を行う必要がありますか?

私はレール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を試すことをお勧めします。これにより、フォームが DRY でシンプルになります。関連付けには非常に優れた機能があります。

次のようなことをして終了します。

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

チェックボックス、ラジオボタン、または必要に応じて複数の値を選択することができます。

それが役に立てば幸い

于 2013-10-25T04:36:38.703 に答える