【发布时间】:2015-05-30 11:58:35
【问题描述】:
我有一个 Word 模型和一个 Category 模型。
单词 has_and_belongs_to_many 类别。 类别 has_and_belongs_to_many Words。
现在,我已经在控制台中设置并运行了所有内容,例如,您可以这样做:
Word.create(title: "Testicles")
testicles = Word.first
Category.create(title: "Genitalia")
genitalia = Category.first
testicles.categories << genitalia
testicles.categories
=> "genitalia"
现在我也可以使用视图中的表单来启动和运行它,但前提是我已经在单独的页面上以自己的表单单独创建了类别,并且与 Word 相同。然后在 Word 显示视图中,我可以创建一个表单来为其分配类别。
但是...我真正想做的是在创建 Word 的同时完成所有这些操作,即在“新单词”视图上。
我在解决如何做到这一点时遇到了很大的问题。我认为我说得对,在那个视图中我只能有一个表单和一个提交,所以我认为我必须以某种方式将所有内容从该表单发送到 WordsController,然后工作那里有一些魔法,但在这里做什么让我很头疼。有人可以帮忙吗?
我尚未创建用户模型或设置身份验证,因此在这方面没有障碍。
模型/word.rb:
class Word < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :categories
validates :title, presence: true
end
模型/类别.rb:
class Category < ActiveRecord::Base
has_and_belongs_to_many :words
validates :title, presence: true
end
schema.rb:
ActiveRecord::Schema.define(version: 20150529144121) do
create_table "categories", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "categories_words", id: false, force: :cascade do |t|
t.integer "category_id"
t.integer "word_id"
end
add_index "categories_words", ["category_id"], name: "index_categories_words_on_category_id"
add_index "categories_words", ["word_id"], name: "index_categories_words_on_word_id"
create_table "words", force: :cascade do |t|
t.string "title"
t.text "description"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "words", ["user_id"], name: "index_words_on_user_id"
end
在尝试了各种 form_tag 魔法(并且失败得很惨)之后,目前我正在使用这个表单:
<%= form_for(@word) do |f| %>
<% if @word.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@word.errors.count, "error") %> prohibited this word from being saved:</h2>
<ul>
<% @word.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title, 'Word' %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :description, 'Definition' %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :categories, 'Category' %><br>
<%= f.text_field :categories %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
在视图中,表单有:
#<Category::ActiveRecord_Associations_CollectionProxy:0x007f16dd834820>
在“类别”框中,但可以将其清除并输入您自己的类别。提交填写了所有字段的表单时,我收到 NoMethodError。
【问题讨论】:
-
查找
accepts_nested_attributes--
标签: ruby-on-rails ruby forms ruby-on-rails-4