In my application I am showing all the products like this
store.html.erb
<% #products.each do |product| %>
<div class="entry" >
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line" >
<span class="price" ><%= number_to_currency(product.price) %></span>
<%= button_to "add to cart", line_items_path(:product_id => product),
:remote => true %>
</div>
</div>
<% end %>
I am sending ajax request with :remote => true and in my line items controller I don't have any .js format
line_items_controller.rb
def create
#cart = current_cart
product = Product.find(params[:product_id])
#line_item = #cart.add_product(product.id)
respond_to do |format|
if #line_item.save
format.html { redirect_to(store_url) }
format.xml { render :xml => #line_item,
:status => :created, :location => #line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => #line_item.errors,
:status => :unprocessable_entity }
end
end
end
What I understand so far is that, since there is no format.js add to cart should not add any product to the cart and nothing should happen. But when I add .js format in the controller
format.js { #current_item = #line_item }
and update the page I see that add to cart worked behind but did not show the result. after updating the page I see 15 or so items in the cart. How is this happening?
Make changes here
<% #products.each do |product| %>
<div class="entry" >
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line" >
<span class="price" ><%= number_to_currency(product.price) %></span>
<%= button_to "add to cart", line_items_path(:product_id => product.id),
:remote => true %> #changes line
</div>
</div>
<% end %>
and for update you have to make .js file for that and update elements and onject of html page through jquery or javascript.
And use only one format so controller method go to one responsive area.
Related
I am trying to build a Q&A app with Ajax on the Index.html.erb. I manage to get the form remotely loading, but when saving the records, the AJAX does not work and the user is taken to the normal show.html.erb. Apart from the Ajax not kicking off, everything works well.
My code is as below:
index.html.erb (Contain a partial for input, and a partial for results)
<div>
<h3 class="section_title"> Q&A </h3>
<hr>
<div id="qanda-form" style="display:none;"> </div>
</div>
<div id="qandas">
<%= render 'qandas/qanda' %>
</div>
_qanda.html.erb (is the partial for results)
<% #qandas.each do |my_qanda| %>
<div class="col-md-9">
<div>
Created <%= local_time(my_qanda.created_at) %>, by <%= User.find_by(id: my_qanda.user_id).full_name %>
</div>
</div>
<% end %>
_form.html.erb (is the input form - has nested form via Cocoon)
<%= simple_form_for #qanda, remote: true do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<div class="col-md-12 form-inputs">
<div class="col-md-8">
<%= f.input :title, label: 'Q&A Title:' %>
</div>
</div>
<div class="qandasquestions">
<%= f.simple_fields_for :qandasquestions do |builder| %>
<% render 'qandas/qandasquestion_fields', f: builder %>
<% end %>
<div class="links btn-group" style="min-height: 34px !important">
<%= f.button :submit, "Publish Q&A", class: "btn btn-default" %>
<%= link_to_add_association 'Add Question', f, :qandasquestions, class: 'btn btn-default', data: {association_insertion_node: '.qandasquestions', association_insertion_method: :append} %>
<%= link_to 'Back', qandas_path, class: "btn btn-default" %>
<%= f.input :company, :as => :hidden, :input_html => {:value => current_user.company} %>
</div>
</div>
<% end %>
Controller:
def index
#qandas = Qanda.all
respond_to do |format|
#qandas = Qanda.all
format.html
format.json
end
end
def create
#qanda = current_user.qandas.build(qanda_params)
respond_to do |format|
if #qanda.save!
#qandas = Qanda.all
format.html { redirect_to #qanda, notice: 'Qanda was successfully created.' }
format.json {render :layout => false}
else
format.html { render :new }
format.json { render json: #qanda.errors, status: :unprocessable_entity }
end
end
end
create.js.erb
$('#qandas').html("<%= j render partial: 'qandas/qanda' %>");
$('#qanda-form').slideUp(350);
new.js.erb
$('#qanda-form').html("<%= j render 'qandas/form' %>");
$('#qanda-form').slideDown(350);
Anybody can see why the Ajax does not kick off please? why am I redirected to the traditional SHOW page please?
Try updating your code to this and let me know if it's working?
def create
#qanda = current_user.qandas.build(qanda_params)
if #qanda.save!
#qandas = Qanda.all
else
#errors = #qanda.errors
end
end
My problem is after I create a new record with ajax I get a NOMETHODERROR and I must reload the page to see the new record.
The Error I get in terminal.
Rendered time_entries/_time_entry.html.erb (3.4ms) Rendered
time_entries/create.js.erb (4.9ms) Completed 500 Internal Server Error
in 41ms (ActiveRecord: 4.4ms)
NoMethodError - undefined method `each' for nil:NilClass:
app/views/time_entries/_time_entry.html.erb:1:in '_app_views_time_entries__time_entry_html_erb___4086905375499854267_70174828432680'
What I do wrong?
time_entries_controller.erb
class TimeEntriesController < ApplicationController
...
respond_to :html, :js
def index
#time_entries = current_user.time_entries.all.order("date DESC")
#time_entries_days = #time_entries.group_by{ |t| t.date.beginning_of_day }
respond_with(#time_entry)
end
def create
#time_entry = TimeEntry.new(timeentry_params)
#time_entry.user_id = current_user.id
respond_to do |format|
if #time_entry.save
format.html { redirect_to #time_entry, notice: 'Arbeitszeit wurde eingetragen' }
format.json { render :show, status: :created, location: #time_entry }
format.js
else
format.html { render :new }
format.json { render json: #time_entry.errors, status: :unprocessable_entity }
format.js
end
end
end
...
_time_entry.html.erb
the partial
<% #time_entries_days.each do |day, time_entries| %>
<% if day.today? %>
<div class="column-12 list-group">Today, <%= l day, format: :dm %></div>
<% else %>
<div class="column-12 list-group"><%= l day, format: :dm %></div>
<% end %>
<ul class="lists">
<% time_entries.each do |time_entry| %>
<li class="list-item" id="time_entry_<%= time_entry.id %>">
<div class="list-item__content">
<h3 class="list-item__title">
<%= link_to time_entry.category.name, time_entry %>
<span><%= l time_entry.start_time, format: :hm %></span> - <span><%= l time_entry.end_time, format: :hm %></span>
</h3>
<p><%= time_entry.note %></p>
</div>
<span class="list-item__label"><%= time_entry.hours %>h</span>
</li>
<% end %>
</ul>
<% end %>
index.html.erb
<% if can? :create, TimeEntry %>
<%= link_to 'Add new Time Entry', new_time_entry_path, remote: true, class: 'btn btn-primary', :data => { :'popup-open' => 'popup-1' } %>
<% end %>
...
<div class="row" id="container_time_entries">
<%= render "time_entry" %>
</div>
create.js.erb for testing
I don't get an alert after I create a new time entry.
alert("HALLO");
create.js.erb normal
$('.modal-bg').hide();
$('.popup').fadeOut(350);
$('#container_time_entries').html("<%= j(render 'time_entry') %>");
You do not set the variable #time_entries_days in your create method, but you need it in your _time_entry.html.erb .
Set it and you should be good to go.
Just added a text field for quantity in my products listing. Regardless of the number I enter in the text field, the cart will show just an increment of one for that click. Of course, I haven't told it to do anything otherwise. But, how do I? I can't find the solution anywhere.
Here's my cart add method :
def add_product(product_id)
line_items.find_or_initialize_by(product_id: product_id).increment(:quantity)
end
and in LineItems #create :
def create
product = Product.find(params[:product_id])
#line_item = #cart.add_product(product.id)
quantity = params[:quantity]
Let me know if there is any other relevant code I can attach. Thanks.
View Code
<%= image_tag(product.image.url, class: 'prodli-img') %>
<h3><%= product.name %></h3>
<p><%= product.description %></p>
<span class="price"><%= number_to_currency(product.price) %></span>
<!--<p> <%= product.colors %> </p>-->
<div id= "text_field"><%= text_field_tag 'quantity' %> </div>
<%= button_to 'Add to Cart', line_items_path(:product_id => product) %>
<% end %>
LI create
def create
product = Product.find(params[:product_id])
#line_item = #cart.add_product(product.id)
#line_item.quantity = params[:quantity]
respond_to do |format|
if #line_item.save
format.html { redirect_to "/#products", notice: "Product added to cart!" }
format.xml { render :xml => #line_item,
:status => :created, :location => #line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => #line_item.errors,
:status => :unprocessable_entity }
end
end
end
You can't easily pass additional parameters with a "button_to"
This should work better
<h3><%= product.name %></h3>
<p><%= product.description %></p>
<span class="price"><%= number_to_currency(product.price) %></span>
<%= form_for :line_item, url: product_line_items_path(product) do |f| %>
<%= f.text_field 'quantity' %>
<%= f.submit 'Add to Cart' %>
<% end %>
Your params in the create method will then look like...
=> {"utf8"=>"V",
"authenticity_token"=>"blah blah"
"line_item"=>{"quantity"=>"12"},
"commit"=>"Add to Cart",
"action"=>"create",
"controller"=>"line_items",
"product_id"=>"1"}
So you can retrieve the quantity with...
#line_item.quantity = params[:line_item][:quantity]
Quantity is an attribute of the #line_item object.
So you should be doing
#line_item.quantity = params[:quantity]
And when you save #line_item it will then have the new value stored.
I want to use two collection #ad_item and #user in my partial. Here is my index erb...
<% if #ad_items.any? && #user.any? %>
<%= render partial: 'yourads/ad_item', collection: {#ad_items,#user} %>
<% end %>
and here is my controller ...
def index
#ad_items = Yourad.all
#user = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #yourads }
end
end
and here is my _ad_item.erb.html partial
<span class="date"><%= ad_item.created_at.to_date() %></span>
<span class="location"><%= ad_item.title %></span>
<div style="float:left"><%= ad_pic #user,ad_item %></div>
<div class="description"><%= ad_item.description %></div>
My helper function is ..
def ad_pic(user,ad)
cl_image_tag("Ad#{user.id}#{ad.id}.jpg", :version => rand(1000000000), :alt => "Ad pic",:width => 70, :height => 70, :crop => :fill)
end
it gives syntax error in ..
<%= render partial: 'yourads/ad_item', collection: {#ad_items,#user} %>
<%= render partial: 'yourads/ad_item', collection: #ad_items ,
locals: {users: #users} %>
and in view
<% for user in users %>
<span class="date"><%= ad_item.created_at.to_date() %></span>
<span class="location"><%= ad_item.title %></span>
<div style="float:left"><%= ad_pic user,ad_item %></div>
<div class="description"><%= ad_item.description %></div>
<% end %>
see Passing Local Variables
<%= render partial: 'yourads/ad_item', :locals => {:ad_items=>#ad_items,:user => #user }%>
you can access #ad_items as ad_items and #user as user in your yourads/ad_item partial
All my code is working nicely, I want to render the same page :new after a user submits a form with your order. The problem is about the :notice message that I want to display Pedido enviado com sucesso. in the page after a submission but it doesn't work. My validation error messages are displayed nicely but I don't know why my success message doesn't.
Any tips?
(Sorry about my code indentation)
My pedidos_controller goes down:
class PedidosController < ApplicationController
def new
#pedido = Pedido.new
1.times do
pessoa = #pedido.build_pessoa
produto = #pedido.produtos.build
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: #pedido }
end
end
def create
#pedido = Pedido.new(params[:pedido])
respond_to do |format|
if #pedido.save
PedidosMailer.delay.registro_do_pedido(#pedido)
PedidosMailer.delay.email_para_cotar_produtos(#pedido)
format.html { redirect_to action: "new", notice: 'Pedido enviado com sucesso.' }
format.json { render json: #pedido, status: :created, location: #pedido }
else
format.html { render action: "new" }
format.json { render json: #pedido.errors, status: :unprocessable_entity }
end
end
end
end
my new.html.erb view:
<p id="notice"><%= notice %></p>
<%= render 'form' %>
my _form.html.erb view:
<%= form_for(#pedido, :html => { :class => "form-contato"}) do |f| %>
<% if #pedido.errors.any? %>
<div id="error_explanation">
<h2>Ocorreram <%= pluralize(#pedido.errors.count, "erro") %></h2>
<ul>
<% #pedido.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="row">
<div class="span4">
<h1>Dados pessoais</h1>
<%= f.fields_for :pessoa do |builder| %>
<%= render 'pessoa_fields', f: builder %>
<% end %>
</div>
<div class="span8">
<h1>Ítens</h1>
<%= f.fields_for :produtos do |builder| %>
<%= render 'produto_fields', f: builder %>
<% end %>
</div>
<div class="span10">
<%= link_to_add_fields "Adicionar mais produtos", f, :produtos %>
</div>
<%= button_tag "Enviar", class: "btn btn-red span10", name: "commit" %>
</div>
<% end %>
my _pessoa_fields.html.erb view:
<fieldset>
<%= f.text_field :nome, class: "span4", placeholder: "Nome" %>
<br />
<%= f.text_field :telefone, class: "span4", placeholder: "Telefone" %>
<br />
<%= f.text_field :email, class: "span4", placeholder: "Email" %>
</fieldset>
my _produto_fields.html.erb view:
<% #lista_de_produtos = ["Qualibom standard", "Qualibom premium", "Bomdemais standard", "Bomdemais premium"] %>
<fieldset class="campos-produtos span10">
<div class="span3">
<%= f.select :nome, options_for_select(#lista_de_produtos, :selected => f.object.nome), :prompt => 'Selecione um produto' %>
</div>
<div class="span3">
<%= f.text_field :quantidade, class: "span3", placeholder: "Quantidade" %>
</div>
</fieldset>
You need to use flash[:notice], not notice, in your view:
<% if flash[:notice] %>
<p id="notice"><%= flash[:notice] %></p>
<% end %>
When you pass a message via the notice: parameter of redirect_to, it's placed into the flash array, which is a special pseduo-session which persist for a single request:
From the ActionController::Redirecting documentation:
It is also possible to assign a flash message as part of the redirection. There are two special accessors for the commonly used flash names alert and notice as well as a general purpose flash bucket.