I'm a beginner programmer on Ruby on Rails.
I have a form that adds an object with attached. The file is stored on the cloud from Amazon S3.
Form done through javascript using ujs. In the form of added parameter: remote: true. But saving does not occur, and there is an error:
Missing template cards/create, application/create with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :slim]}.
Help what to do?
my form:
= simple_form_for [#deck, #card], remote: true, authenticity_token: true do |f|
p
= f.input :original_text, as: :string, label: 'Original text', input_html: { class: 'form-control' }
p
= f.input :translated_text, as: :string, label: 'Translated text', input_html: { class: 'form-control' }
p
= f.file_field :picture
p
= f.button :submit, data: { disable_with: 'Сохраняется...' }, class: "btn btn-success btn-lg btn-block", id: "btn-login"
my new.js.erb:
$("#modal-window").html("<%= j render 'cards/new' %>");
my create.js.erb:
$("#modal-window").modal("hide");
$(".cards-index").html('<%= j render 'cards/all', cards: #cards %>');
$("#card_title").val('');
Great! Problem solved.
Added gem 'remotipart'
2 Added to the file application.js after //= require jquery_ujs string //= require jquery.remotipart
3 Added to the form string authenticity_token: true
Related
I've seen numerous posts about this issue but none of them have helped.
As a lot of people, I'm trying to have a delete link to delete heore order_items.
When I had Turbolinks working I had no issue with those links, except that because of Turbolinks my pages couldn't load properly. I removed it and now I'm trying to fix my links.
Here's my template:
_cart_row_html.erb
<%= simple_form_for order_item, authenticity_token: true, remote: true do |f| %>
<td><%= product.reference %></td>
<td><%= product.name %></td>
<td><%= f.number_field :quantity, value: order_item.quantity.to_i, class: "form-control", min: 1 %></td>
<td><%= f.button :submit, "Mettre à jour la quantité", class: "btn btn-primary" %></td>
<td><%= link_to '<i class="fas fa-trash"></i>'.html_safe, 'data-method' => :delete %> </td>
<td><%= number_to_currency order_item.total_price, locale: :fr %></td>
<% end %>
My routes.rb:
Rails.application.routes.draw do
root to: "home#index"
devise_for :users, controllers: { registrations: "registrations", sessions: "sessions" }
resource :cart, only: [:show]
resources :order_items, only: [:create, :update, :destroy]
resources :categories
resources :products
get 'orders/validate_cart', as: 'validate_cart'
get 'orders/validate_coordinates', as: 'validate_coordinates'
#get 'order_items/create'
#get 'order_items/update'
#get 'order_items/destroy'
get 'carts/show'
get '/articles/:category', to: 'articles#index', as: 'list_product_by_category'
get '/articles/:categories/:id', to: 'articles#show', as: 'product_detail'
get '/users', to: 'users#index', as: 'users_list'
get 'dashboard' => 'dashboard#index'
end
My application.js:
//= require jquery3
//= require rails-ujs
//= require activestorage
//= require popper
//= require bootstrap-sprockets
//= require akame.bundle
And finally my oder_items_controller.rb
class OrderItemsController < ApplicationController
def create
#order = current_order
#order_item = #order.order_items.new(order_item_params)
#order.save
session[:order_id] = #order.id
redirect_to request.referrer
end
def update
#order = current_order
#order_item = #order.order_items.find(params[:id])
#order_item.update_attributes(order_item_params)
#order_items = #order.order_items
#order.save
redirect_to request.referrer, notice: "La quantité a bien été mise à jour"
end
def destroy
#order = current_order
#order_item = #order.order_items.find(params[:id])
#order_item.destroy
#order_items = #order.order_items
if #order_items.length <=0
reset_session
redirect_to carts_show_path
else
redirect_to carts_show_path, notice: "Le produit a bien été supprimé"
end
end
private
def order_item_params
params.require(:order_item).permit(:quantity, :product_id)
end
end
So far I've tried all of those solutions:
- Replace method by data-method
- Use <%= javascript_include_tag :application %> into my application.html.erb file
- Check if
//= require jquery3
//= require rails-u
are in my application.js
with the help of those posts for e.g.: I can't delete a post in Rails
Can't Edit Or Delete Javascript in Rails
EDIT: when I use this path <td><%= link_to '<i class="fas fa-trash"></i>'.html_safe, order_item_path(#order_item), 'data-method' => :delete %> </td> I have this error : "No route matches {:action=>"update", :controller=>"order_items", :id=>nil}, missing required keys: [:id]"
What am I missing ? It's driving me nuts for days now ...
In your
<%= link_to "Ajouter au panier", order_item_path(#order_item), class: "btn btn-primary" %>
Your path should look like this order_item_path(#order_item), method: :delete so you point to the destroy action. It also looks like you are using #order_item and it's nil, in your _cart_row.html.haml you have a local variable order_item so you probably should use that.
Hope it helps
I've changed my code to <%= link_to '<i class="fas fa-trash"></i>'.html_safe, order_item_path(order_item), 'data-method' => :delete %> and it DOES work even if I'm pretty sure I tested that before. Anyway I'm glad it works. I'm upvoting your answer. Thanks !
I'm a beginner to Rails and I'm following a tutorial to build a Todo App.
When I try to click the button in the browser (in the application.html.haml code below) nothing happens. It is as if it is unresponsive. I see when I hover over the button it is supposed to direct me to localhost:3000/tasks/new.
Here's a snapshot of how the page looks as of now:
In the tutorial, there is a modal that is used to render the new todo task. The code for the modal is in new.js.erb in view > tasks:
m = $('#modal');
m.html('<%= j(render partial: 'task_form', locals: {task: #task}) %>');
m.modal('show');
The partial task_form.html.haml code is:
.modal-header
%h1 New Task
= simple_form_for task, class: 'clearfix' do |f|
.modal-body
= f.input :title
= f.input :note
= f.input :completed
.modal-footer
= f.submit 'Save', class: 'btn btn-primary'
The code for home.html.haml is:
.container
- if #tasks.empty?
%span.text-warning There are no tasks!
- else
%table.table.table-hover.table-bordered
%thead
%tr
%th Title
%th Created at
%th Completed
%tbody
- #tasks.each do |task|
%tr
%td
%strong= task.title
%td.text-info= task.created_at
%td.text-success= task.completed
#modal.modal.fade
And for the application.html.haml is:
!!!
%html
%head
%title Todo
= csrf_meta_tags
= csp_meta_tag
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'
%body
.container
.jumbotron.text-center
%h1
ToDo
%p
Welcome to the tutorial's ToDo application
= link_to 'New task', new_task_path, class: 'btn btn-primary', remote: true
= yield
I tried looking for a solution everywhere but I couldn't find it. I thought I'd post it here for help from any good samaritans..Could you let me know why I cannot see the modal?
Thanks a lot for any help.
I finally got it. I forgot to install the gem 'jquery-rails' and make the necessary additions to the application.js and application.scss. Restarting the server after that resulted in a modal. Thanks!
I've read through other questions and the cocoon github wiki as well, tried out the sample Rails 4 demo (which works) but I can't get the callbacks to fire on my project.
My gem file is a bit long but the most relevant gems IMHO are cocoon from master (1.2.6), thrubyracer, turbolinks, and spring.
form (note that data-no-turbolinks false and true have had no effect):
%div{"data-no-turbolink" => "false"}
= simple_form_for #course, html: { class: "pure-form"} do |f|
= f.error_notification
.form-inputs
= f.input :name, label: false, placeholder: 'Nombre del Curso', html: {id: 'nombre'}
#subjects.well
= f.input :materia, collection: #materia, prompt: 'Seleccione una materia', value_method: :name
= f.input :tema_de_curso, collection: #tema, prompt: 'Seleccione el tema del curso', value_method: :name
= f.input :grado, collection: #grado, prompt: 'Seleccione el grado', value_method: :name
#bimesters.well
= f.simple_fields_for :bimesters do |bimester|
= render 'bimester_fields', :f => bimester
.links
= link_to_add_association 'Agregar Bimestre', f, :bimesters, class: 'btn btn-primary'
.form-actions
= f.button :submit, class: 'btn btn-success btn-block btn-lg'
partial:
.nested-fields
= f.input :name, collection: #bims, label: 'Bimestre', prompt: 'Seleccione el bimestre', value_method: :name
= link_to_remove_association 'Eliminar Bimestre', f, class: 'btn btn-danger pull-right', style: 'margin-bottom: 1em; '
JS (tried with this extract from the demo project to keep it simple):
$(document).ready(function() {
$('#bimesters').bind('cocoon:before-insert', function(e,task_to_be_added) {
console.log(task_to_be_added);
task_to_be_added.fadeIn('slow');
task_to_be_added.fadeIn('slow');
});
});
Relationship is working correctly as well so models and controller should be fine. I've got the sensation that it might be something to do with turbolinks but all tested permutations have failed.
My main goal is to get the id of the elements that have been created because I'm filtering other nested form partials based on these selections.
I am currently working with the Acts_As_Votable gem in Ruby to use a Like link on each of my posts so that users can vote. I found a great answer on here that helped be do exactly that but I'm trying to figure out how I can use a heart icon image instead of the Like/Dislike text. I want the image to update without refreshing, just like the text links do but can't figure out the logic. Here is the current code I am using:
controllers/prides_controller.rb
def like
#pride = Pride.find(params[:id])
#pride.liked_by current_user
if request.xhr?
render json: { count: #pride.get_likes.size, id: params[:id] }
else
redirect_to #pride
end
end
def dislike
#pride = Pride.find(params[:id])
#pride.disliked_by current_user
if request.xhr?
render json: { count: #pride.get_likes.size, id: params[:id] }
else
redirect_to #pride
end
end
prides/show.html.erb
<div class="single-heart-this">
<% if current_user.liked? #pride %>
<span class="heart-icon-loved">
<%= link_to "Dislike", dislike_pride_path(#pride), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Like', toggle_href: like_pride_path(#pride), id: #pride.id } %></span>
<% else %>
<span class="heart-icon">
<%= link_to "Like", like_pride_path(#pride), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Dislike', toggle_href: dislike_pride_path(#pride), id: #pride.id } %></span>
<% end %>
<span class="heart-no" data-id="<%= #pride.id %>"><%= #pride.get_likes.size %></span>
<% end %>
</div>
javascript/pride.js.erb
# Rails creates this event, when the link_to(remote: true)
# successfully executes
$(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
# the `data` parameter is the decoded JSON object
$(".heart-no[data-id=#{data.id}]").text data.count
return
javascript/prides.js.coffee
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
$(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
# update counter
$(".heart-no[data-id=#{data.id}]").text data.count
# toggle links
$("a.vote[data-id=#{data.id}]").each ->
$a = $(this)
href = $a.attr 'href'
text = '$a.text()'
$a.text($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
$a.data('toggle-text', 'text').data 'toggle-href', href
return
return
Thanks for your help.
Try this?
Add: class: "Change_me" to your link
<%= link_to image_tag("Dislike.png"), dislike_pride_path(#pride), class: 'vote', method: :put, remote: true, data: { toggle_href: like_pride_path(#pride), id: #pride.id }, class: "change_me" %>
src: link_to image_tag with inner text or html in rails
In your coffeescript, change the image src
$(".change_me").attr 'src', '/like.png'
src: Rails 3.1 CoffeeScript/JQuery - How to change the source of an image in a div?
Hi have problem with cocoon: https://github.com/nathanvda/cocoon and datetimepicker:http://xdsoft.net/jqplugins/datetimepicker/. When I add through cocoon new nested field my calendar not showing up. I think that I must user cocoon after:insert event in my javascript file but I tried every way and this is not working.
This is my views:
costs.html.haml
= simple_form_for [:partners, #car], url: wizard_path do |f|
= f.simple_fields_for :costs do |cost|
= render 'cost_fields', f: cost
#links
= link_to_add_association '+', f, :costs
= link_to t('cars.back'), previous_wizard_path
= f.submit t('cars.next'), class: 'btn btn-primary'
and my cost_fields partial:
.nested-fields
%table.table.table-striped.table-bordered.dupa
%thead
%th.field
= f.association :cost_type
%th.field
= f.input :netto_price
%th.field
= f.input :document_number
%th.field
= f.association :vat
%th.field
= f.input :type_of_cost
%th.field
= f.input :date, as: :string , :input_html => { :class => 'date' }
= link_to_remove_association "X", f
Any ideas?
As this post eludes, this is because the dynamically added elements are not yet in the DOM.
Try to add a class or id before your nested simple fields (this will already be in the DOM), e.g.:
#container
= f.simple_fields_for :costs do |cost|
= render 'cost_fields', f: cost
Then in your javascript file:
$(document).on('ready page:change', function() {
$('#container').on('cocoon:after-insert', function() {
$('.datetimepicker').datetimepicker();
})
})
Also, I've used this datepicker gem, which allows you to generate a wrapper input/custom date/time fields
= f.input :date, :as => :date_picker