【问题标题】:Rails form_for, creating event with categorizationRails form_for,用分类创建事件
【发布时间】: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


    【解决方案1】:

    正如您提到的,您是 Rails 新手,您会发现 cocoon gem 非常有趣。你可以实现你想要的。而且代码会更干净。

    我没有要评论的点,这就是我给出这个答案的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      相关资源
      最近更新 更多