【发布时间】:2017-05-04 23:57:32
【问题描述】:
我对 ruby on rails 有点陌生,我一直在阅读有关协会的文档并且我一直很轻松(通常快速的谷歌搜索可以解决我的大部分疑问)但是最近我遇到了问题做一件看似简单的事。
我想做的是创建一个事件,链接到现有的类别。
事件模型
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 %>
我之前在 Category db 中填充了一些类别,所以剩下要做的就是在创建事件时,同时创建一个与新事件和所选类别相关联的类别。但我尝试过的东西似乎不起作用。
其他事情似乎工作正常,每当我尝试提交事件时,除了分类之外,所有东西都按预期填充。
【问题讨论】:
标签: ruby-on-rails has-many-through belongs-to nested-form-for