Rails form_for,用分类创建事件

时间:2017-05-04 23:57:32

标签: ruby-on-rails has-many-through belongs-to nested-form-for

我对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 %>

我之前使用某些类别填充了类别数据库,因此剩下要做的是创建事件时,还要创建一个链接到新事件和所选分类的分类。但我尝试过的东西似乎没有用。

其他事情似乎工作正常,每当我尝试提交事件时,所有内容都按预期填充,但分类除外。

1 个答案:

答案 0 :(得分:0)

正如您所说,您不熟悉rails,您会发现这个cocoon gem非常有趣。你可以实现你想要的。代码会更清晰。

我没有评论要点,这就是为什么我这样做的答案。