I am newbie. I am trying to develop a simple web application involving shops and candies where a shop can have many candies.
I have the following code in my shops/show.html.erb which displays list of candies twice.
<% i=0 %>
<% for candy in @shop.candies do %>
<% i+=1 %>
<%= i %> <%= candy.name %>
<% end %>
<%= form_for([@shop, @shop.candies.build]) do |f| %>
<%= render(:partial => 'form',
:locals => {:f => f, :header => "Add a Candy",
:placeholder => "Enter a candy name"}) %>
<% end %>
<% i=0 %>
<% for candy in @shop.candies do %>
<% i+=1 %>
<%= i %> <%= candy.name %>
<% end %>
My code in _form.html.erb for creating a new candy:
<%= f.text_field(:name, :placeholder=> placeholder, :class=>"form-control custom-input")%>
<%= button_tag( :class => "btn btn-primary mb-2 btn-custom btn-custom-sc") do %>
<i class="fas fa-plus icon"></i>
<% end %>
Code of Shops Controller:
class ShopsController < ApplicationController
def show
@shop = Shop.find(params[:id])
@unshelved_candies = @shop.candies.unshelved_candies
end
private
def shop_params
params.require(:shop).permit(:name)
end
end
Code of Candies Controller:
class CandiesController < ApplicationController
def create
@shop = Shop.find(params[:shop_id])
@candy = @shop.candies.create(candy_params)
redirect_to(shop_path(@shop))
end
private
def candy_params
params.require(:candy).permit(:name)
end
end
end
When I run the code and view it on browser, I notice that it creates an empty candy in the second loop (not in database). However, when I remove the form for creating candies, it behaves as it should. I am unable to understand why it's looping one more time and displaying blank value. The output of the first loop is the correct one:
- Candy 1
- Candy 2
- Candy 3
And the output of second loop is:
- Candy 1
- Candy 2
- Candy 3
- [<---Empty. I am not inserting anything new to the database]
Can anybody tell me why it is displaying a blank value in second loop and how to prevent this extra iteration?