2

I am trying to learn using rails. I was following http://guides.rubyonrails.org/getting_started.html I added the associated model. but when I create the new event..it also duplicates it.

class EventsController < ApplicationController

def create
    @category = Category.find(params[:category_id])
    @event = @category.events.create(event_params)

    redirect_to category_path(@category)
end

def destroy
    @category = Category.find(params[:category_id])
    @event = @category.events.find(params[:id])
    @event.destroy
    redirect_to category_path(@category)
end
private
def event_params
    params.require(:event).permit(:event, :genus, :description)
end

end

Here is model :

class Event < ActiveRecord::Base
  belongs_to :category

end

Here is the form I am using to save event in the particular category:

<%= form_for ([@category, @category.events.build]) do |f| %>
<p>
    <%= f.label :name %><br>
    <%= f.text_field :event %>
</p>
<p>
    <%= f.label :genus %><br>
    <%= f.text_field :genus %>
</p>
<p>
    <%= f.label :description %><br>
    <%= f.text_area :description %>
</p>
<p>
    <%= f.submit %>
</p>

This is the show view code :

<p>


<strong>Title:</strong>
  <%= @category.name %>
</p>

<p>
  <strong>Text:</strong>
  <%= @category.key %>
</p>

<h2>Events</h2>
<%= render @category.events %>

<h2>
    Add Event
</h2>
<%= render 'events/form' %>


<%= link_to 'Back', categories_path %>

Thing is when i create record..it creates duplicate entry and delete record it deletes both entries.

I cant figure out whats wrong with my code. I just followed the guide..

This is how records are duplicated

Ryan Cyrus
  • 309
  • 5
  • 14

1 Answers1

0

Ok, I found out what was wrong. It was <% @category.events.each do |event| %> line in _event.html.erb It was creating duplicate views. Thanks everyone for help

<% @category.events.each do |event| %>
  <p>
    <strong>Event Name:</strong>
    <%= event.name %>
  </p>

  <p>
    <strong>Genus:</strong>
    <%= event.genus %>
  </p>
  <p>
    <strong>Description:</strong>
    <%= event.description %>
  </p>

  <p>
    <%= link_to 'Destroy Event', [event.category, event], method: :delete, data: {confirm: 'Are you sure?'} %>
  </p>
<% end >

It should be like this :

  <p>
    <strong>Event Name:</strong>
    <%= event.name %>
  </p>

  <p>
    <strong>Genus:</strong>
    <%= event.genus %>
  </p>
  <p>
    <strong>Description:</strong>
    <%= event.description %>
  </p>

  <p>
    <%= link_to 'Destroy Event', [event.category, event], method: :delete, data: {confirm: 'Are you sure?'} %>
  </p>

What I understand is that when <%= render @category/events %> redirects to this page. It was querying for data two times.

Correct me if i am not right?

but i dont understand why was this generating duplicate records?

Ryan Cyrus
  • 309
  • 5
  • 14