我对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 %>
我之前使用某些类别填充了类别数据库,因此剩下要做的是创建事件时,还要创建一个链接到新事件和所选分类的分类。但我尝试过的东西似乎没有用。
其他事情似乎工作正常,每当我尝试提交事件时,所有内容都按预期填充,但分类除外。