0

我有點新的紅寶石的軌道上,我一直在閱讀關於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 %> 

我以前填充某些類別的分類數據庫,所以還剩下些什麼做的是在創建一個事件,還可以創建一個分類是與新事件和所選分類相關聯。但我嘗試過的東西似乎並不奏效。

其他事情似乎工作正常,每當我嘗試提交事件時,除分類外,所有事情都按預期填充。

回答

0

正如你所說,你是一個新的rails,你會發現這個cocoon gem非常有趣。你可以達到你想要的。代碼將更清潔。

我沒有要評論的觀點,這就是爲什麼我將此作爲答案。