Ruby on rails 轨道:选择要关联的多个标记对象
所以我正在做一个项目,我有一个文档对象(基本上是一个电子图书馆应用程序),我有一堆标记对象,我希望能够与之关联。目前我有一个Ruby on rails 轨道:选择要关联的多个标记对象,ruby-on-rails,ruby-on-rails-3,forms,Ruby On Rails,Ruby On Rails 3,Forms,所以我正在做一个项目,我有一个文档对象(基本上是一个电子图书馆应用程序),我有一堆标记对象,我希望能够与之关联。目前我有一个has\u和\u属于\u许多两者之间的关联。我的问题是标签的形式,从可用标签列表中选择与该文档关联的最佳方式是什么?我需要在控制器里做些什么花哨的工作才能做到这一点吗 我使用的是rails 3.2 下面是一些代码: # This is the text model # It will not have an attachment but instead it's child
has\u和\u属于\u许多两者之间的关联。我的问题是标签的形式,从可用标签列表中选择与该文档关联的最佳方式是什么?我需要在控制器里做些什么花哨的工作才能做到这一点吗
我使用的是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
首先,我建议尝试一下,它会使你的表格变得干练和简单。它们有很好的联想功能
您将结束这样的操作:
= simple_form_for @text do |f|
...
= f.association :tags, as: :check_boxes
可以是复选框、单选按钮,如果需要,也可以是带有多个值的选择
希望能有所帮助谢谢,这很有效,但你必须做简单的表格,而不是表格。我编辑了答案以反映这一点。
= 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'
= simple_form_for @text do |f|
...
= f.association :tags, as: :check_boxes