Rails的form_for,创建事件与分类
问题描述:
我有点新的红宝石的轨道上,我一直在阅读关于assosiations的文档,我一直有一个简单的时间(通常快速谷歌搜索解决了我的疑惑大部分)然而最近我遇到了一个看起来很容易做的事情。Rails的form_for,创建事件与分类
我想要做的是创建一个事件,链接到一个现有的类别。
事件模型
class Event < ApplicationRecord
has_many :categorizations
has_many :categories, through: :categorizations
accepts_nested_attributes_for :categorizations
.
.
.
end
分类模型
class Category < ApplicationRecord
has_many :categorizations
has_many :events, through: :categorizations
end
分类模型
class Categorization < ApplicationRecord
belongs_to :event
belongs_to :category
end
事件控制器
class EventsController < ApplicationController
def new
@event = Event.new
end
def create
@user = User.find(current_user.id)
@event = @user.events.create(event_params)
if @event.save
redirect_to root_path
else
redirect_to root_path
end
end
private
def event_params
params.require(:event).permit(:name, category_ids:[])
end
这里是形式,这是我认为问题在于:
<%= form_for @event, :html => {:multipart => true} do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.fields_for :categorizations do |categories_fields|%>
<% categories = [] %>
<% Category.all.each do |category| %>
<% categories << category.name %>
<% end %>
<%= categories_fields.label :category_id, "Category" %>
<%= categories_fields.select (:category_id, categories) %>
<% end %>
.
.
.
<%= f.submit "Create"%>
<% end %>
我以前填充某些类别的分类数据库,所以还剩下些什么做的是在创建一个事件,还可以创建一个分类是与新事件和所选分类相关联。但我尝试过的东西似乎并不奏效。
其他事情似乎工作正常,每当我尝试提交事件时,除分类外,所有事情都按预期填充。