ruby-on-railshas-many-throughbelongs-tonested-form-for

Rails form_for, creating event with categorization


I'm kinda new to ruby on rails, I've been reading documentation on assosiations and I've been having an easy time (and usually a quick google search solves most of my doubts) however recently I'm having problems with a seemingly easy thing to do.

What I'm trying to do is to create an Event, linked to an existing Category.

Event model

class Event < ApplicationRecord

  has_many :categorizations
  has_many :categories, through: :categorizations
  accepts_nested_attributes_for :categorizations
  .
  .
  .
end

Category model

class Category < ApplicationRecord
  has_many :categorizations
  has_many :events, through: :categorizations
end

Categorization model

class Categorization < ApplicationRecord
  belongs_to :event
  belongs_to :category
end

Event controller

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

Here is the form, which is where I think the problem lies:

<%= 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 %>

I previously populate the Category db with some categories, so what's left to do is to while creating an event, also create a categorization that is linked both to the new event and the chosen Categorization. but the things I've tried don't seem to be working.

Other things seem to be working ok, whenever I try to submit the event all things are populated as expected except the categorization.


Solution

  • As you mentioned that you are new to rails, you'll find this cocoon gem very interesting. You can achieve what you wanted. And the code will cleaner.

    I don't have the points to comment, that's why I am giving this as an answer.