RoR: destroy.js.erb not being run along with destroy action - javascript

My issue is that I expect on calling the destroy action of my swipe controller (which does work) that it would then call the javascript in the file app/views/swipes/destroy.js.erb. The idea being that on calling this file it will refresh my my-deck div and provide an updated web page. Unfortunately, although my destroy action is working, it doesn't seem to be calling the js correctly and I have to refresh the webpage to see that the item has been deleted.
Here are the relevant files, let me know if more info could be useful.
app/controllers/swipes_controller.rb
class SwipesController < ApplicationController
def new
end
app/views/swipes/destroy.js.erb
$(".my-deck").alert("Foo");
app/views/my_deck/show.html.erb
<p> Welcome to my deck! </p>
<p> When this is working your right swiped events should appear beautifully below! </p>
<div class="my-deck">
</div>
app/views/my_deck/_my_deck.html.erb
<p class="text-center">
There are no items in your shopping cart. Please <%= link_to "go back", home_path %> and add some items to your cart.
</p>
<% end %>
"app/views/my_deck/_card_row.html.erb"
<div class="well">
<div class="row">
<div class="col-xs-8">
<h4><%= event_id %></h4>
</div>
<div class="col-xs-4">
<div class="row">
<div class="col-xs-4">
</div>
<div class="col-xs-8 text-right">
<div class="btn-group">
<%= link_to "Delete", myCard, { data: { confirm: "Are you sure you wish to delete the product '#{myCard.event_id}' from your cart?"}, method: :delete, remote: true, class: "btn btn-danger" } %>
</div>
</div>
</div>
<% end %>
</div>
</div>
</div>
Heres the output of my rails server when I click delete:
Swipe Load (0.8ms) SELECT "swipes".* FROM "swipes" WHERE "swipes"."id" = $1 LIMIT 1 [["id", 48]]
(0.1ms) BEGIN
(1.6ms) COMMIT
Rendered my_deck/_my_deck.html.erb (74.5ms)
Rendered swipes/destroy.js.erb (79.0ms)
Completed 500 Internal Server Error in 91ms (ActiveRecord: 3.0ms)
ActionView::Template::Error (undefined method `size' for nil:NilClass)
app/views/my_deck/_my_deck.html.erb:1:in `_app_views_my_deck__my_deck_html_erb___162867021113944140_70146212264540'
app/views/swipes/destroy.js.erb:1:in `_app_views_swipes_destroy_js_erb__359810691289434442_70146212224340'
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.6ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (0.7ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/actionpack-4.2.4/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb (8.9ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/web-console-2.2.1/lib/web_console/templates/_markup.html.erb (0.6ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/web-console-2.2.1/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.2ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/web-console-2.2.1/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.3ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/web-console-2.2.1/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.5ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/web-console-2.2.1/lib/web_console/templates/console.js.erb within layouts/javascript (14.6ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/web-console-2.2.1/lib/web_console/templates/main.js.erb within layouts/javascript (0.3ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/web-console-2.2.1/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.4ms)
Rendered /home/tomos/.rvm/gems/ruby-2.2.3/gems/web-console-2.2.1/lib/web_console/templates/index.html.erb (30.9ms)
If someone could help me figure out why app/views/swipes/destroy.js.erb is not running that'd be great. I'm following this tutorial.

This happens because destroy.js.erb
$(".my-deck").alert("Foo");
$(".my-deck").html("<%= escape_javascript(render 'my_deck/my_deck') %>");
renders app/views/my_deck/_my_deck.html.erb, that, in order, executes this line:
<% if #myDeck.size == 0 %>
Since you don't define #myDeck anywhere (neither in your controller's destroy action, nor in destroy.js.erb) this variable initializes to nil, which doesn't have any .size method, that causes error you have.
To fix the error you need either to properly initialize #myDeck var or to change your template so it won't access to uninitialized vars anymore (for example, remove line $(".my-deck").html("<%= escape_javascript(render 'my_deck/my_deck') %>");).
Have a nice day!

I had a similar problem when testing some ajax events, because something was missing on my action:
Here is what I added inside my destroy action:
respond_to do |format|
format.js
end
Try change your destroy to:
def destroy
#swipe = Swipe.find(params[:id])
if #swipe.destroy
redirect_to myDeck_path
end
respond_to do |format|
format.js
end
end
I hope it works for you.

Related

Rails 5 using Kaminari twice on same page renders full page in partial

a controller action has two sets of data (originating form the same class, but drawn from different queries
#usercontents = Usercontent.where(contenttype_id > ?, 1).page params[:page]
#points = Usercontent.where(contenttype_id = ? ', 1]).page params[:page]
The views has partials who in turn invoke their own partials
<%= render 'points' %>
and
<%= render 'contents' %>
_contents.html.erb partial
<%= paginate #usercontents, remote: true, previous_label: t('navigate.previous'), next_label: t('navigate.next'), params: {anchor: 'panel3'} %>
<div id=usercontents class='tableize'>
<%= render partial: 'usercontents/usercontent', collection: #usercontents %>
</div>
_points_html.erb partial
<%= paginate #points, remote: true, previous_label: t('navigate.previous'), next_label: t('navigate.next'), params: {anchor: 'panel2'} %>
<div id=points class='tableize'>
<%= render partial: 'point', collection: #points %>
</div>
As the view alludes to, the pagination collections are in seperate tabulations of the page.
The end result is that pages do get paginated, but the call has three problems:
Instead of having a XHR call for just the collection, all assets are being invoked
rendering is not occuring for just the partial but the whole page (including stringified javascript!)
the pagination rendering is being placed after the partial, not in substitution of. calling another page just adds the new page to the end of previous block.
What is incorrect in this setup?

Rails redirect_to not rendering

I'm at a logical 'fork' in the road where a user can pick a payment plan for my service or use a 'coupon code', which they've pre-purchased. I have the functionality for selecting the 'payment plan' working and now I'm working on the other fork in the road, but feel like I'm going about it all wrong. I ended up copying and adapting the 'payment plan' functionality with the inclusion of coupon_code... so, I have a separate route if they select to use a coupon as well a separate views and controller methods.
In the end, I'll need to create a 'customer' for future payment, instead of the functionality that I have in place that creates a 'customer' and immediately charges them, hence the need for the fork in the road (i think).
Of course, I could me going about this all wrong, so please let me know if there is a better way.
Here's what I have for attempting to get the coupon code stuff working, however, it's not redirecting to the new view, even though the logs say it is, the 'POST' seems to work fine. I'm not sure why the log shows that it's trying to render packages/show.json.jbuilder which I assume is the problem here:
console log
Started POST "/packages/coupon" for 127.0.0.1 at 2016-03-25 10:52:17 -0500
Processing by PackagesController#coupon as JS
Parameters: {"utf8"=>"✓", "coupon_code"=>"59ee713a79b44af780c7b7c54f046570"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."id" = 16 ORDER BY "users"."id" ASC LIMIT 1
Role Load (0.6ms) SELECT "roles".* FROM "roles" INNER JOIN "roles_users" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."deleted_at" IS NULL AND "roles_users"."user_id" = $1 [["user_id", 16]]
Device Load (34.9ms) SELECT "devices".* FROM "devices" WHERE "devices"."identifier" = '59ee713a79b44af780c7b7c54f046570' ORDER BY "devices"."id" ASC LIMIT 1
Redirected to http://localhost:3000/packages/coupon
Completed 302 Found in 59ms (ActiveRecord: 36.4ms)
Started GET "/packages/coupon" for 127.0.0.1 at 2016-03-25 10:52:17 -0500
Processing by PackagesController#show as JS
Parameters: {"id"=>"coupon"}
User Load (0.9ms) SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."id" = 16 ORDER BY "users"."id" ASC LIMIT 1
Role Load (0.6ms) SELECT "roles".* FROM "roles" INNER JOIN "roles_users" ON "roles"."id" = "roles_users"."role_id" WHERE "roles"."deleted_at" IS NULL AND "roles_users"."user_id" = $1 [["user_id", 16]]
Rendered packages/show.json.jbuilder (8.5ms)
Completed 200 OK in 51ms (Views: 44.8ms | ActiveRecord: 1.4ms | Solr: 0.0ms)
views/packages/index.html.erb
<!-- Modal -->
<div class="modal fade" id="couponModal" tabindex="-1" role="dialog" aria-labelledby="couponModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="couponModalLabel">Enter Coupon Code</h4>
</div>
<div class="modal-body">
<p>Enter your pre-purchased coupon code in the area below.</p>
<%= form_tag('/packages/coupon', id: 'coupon_form', remote: true) do %>
<%= text_field_tag 'coupon_code', nil, placeholder: 'Coupon Code' %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<%= submit_tag "Submit Code", class: "btn btn-success" %>
</div>
<% end %>
</div>
</div>
</div>
controllers/packages_controller.rb
# Route for using a coupon code
def coupon
device = Device.where(identifier: params[:coupon_code]).first
if !device.nil? && device.is_provisioned
# TODO: Route to new route that just adds customer to stripe
redirect_to controller: 'packages', action: 'coupon'
else
# TODO: Back to pacakge page letting them know the coupon is invalid.
puts false
end
end
views/packages/coupon.html.erb
<div class="row login-container column-seperation">
<div class="col-md-6 col-md-offset-3">
<h2 class="text-center">You're almost done! You've already paid for the service, so we just need to collect your payment information for future purchases.</h2>
<br/>
<div class="row">
<div align="center" class="col-md-12">
<%= render 'coupon_form' %>
</div>
</div>
</div>
</div>
config/routes.rb
match '/packages/coupon', to: 'packages#coupon', via: [:post, :get]
If you want to call asynchronously, you can use
remote: true
<%= form_tag('/packages/coupon', id: 'coupon_form', remote: true) do %>
To fetch it, create file in /packages folder /create.js.erb file.
console.log("<%= j render #package %>");
check browser console to see fetched data.
$('nav').after("<div class='alert alert-success'> Package Successfully Added </div>");
$('#packages').append("<%= j render #package %>");

Rails 4 - Display data inside a bootstrap modal via ajax

I have a pretty simple Ruby On Rails app with bootstrap 3 for the front end: I have Deals, and each Deal has_many Opportunities.
On each Deal page (url of deal 1 is like myapp.com/id=1), I want to have a textual link that says "view deal's opportunities" and that must trigger when clicked the appearance of content inside a Bootstrap modal.
Very basic but for specific reasons, I wish to load the content of the modal via Ajax.(the content is not visible when users load the Deal page but only when they click on the link 'view deal's opportunities'
I found many resources online for Rails4/ajax/Forms and other stuff with Ajax but not a simple "display content/text" inside a modal via Ajax. Should be easy but I'm stuck.
controller/deals_controller.rb
def showcase
deals = Deal.friendly.find(params[:id])
respond_to do |format|
format.html # showcase.html.erb
format.json { render json: #deal }
end
end
def show_opportunities
#opportunities = Opportunity.where('deal_id = ? AND deal_type = ?',
#deal.id, "high tech").first
respond_to do |format|
format.js
end
end
app/views/deals/showcase.html.erb
this is the beginning
<%= render 'deals/deal_info_zone' %>
this is the end
views/deals/_deal_info_zone.html.erb
<div id="zoneA">
<div style="color:red;padding-top: 150px;">
<%= link_to "view infos of Opportunities", deal_opportunities_modal_path, remote: true %>
</div>
</div>
Here is the modal I'd like to trigger via ajax: views/deals/opportunity_modal
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<%= #opportunity.name %> <br/>
</div>
</div>
</div>
</div>
routes.rb
match '/deals/:id', # this is the Deal page
to: 'deals#showcase',
via: 'get',
as: :deal_page
match '/opportunity_modal',
to: 'deals#show_opportunities',
via: 'get',
as: :deal_opportunities_modal
I'm a rookie in RoR and have never used ajax, ujs maybe... I feel it's missing things like javascript code and xhr request...
The current situation is this one: when I go on a Deal page (for ex page /deal id=1) the textual link "view infos of Opportunities". and the browser points to http://localhost:3000/opportunity_modal but it does not trigger anything when I click on it. Nothing happens. Nothing gets displayed btw on firebug console.
When you click a remote: true link, rails is not looking for opportunity_modal.html.erb, it's looking for opportunity_modal.js.erb. What you need to to do is put your modal in a partial, then render it with JavaScript.
Put your modal code into a partial named views/deals/_opportunity_modal.html.erb.
Create a views/deals/opportunity_modal.js.erb file that will render and show the modal when the this action is triggered.
$('body').append('<%= j render partial: "views/deals/opportunity_modal" %>');
$('#myModal').modal('show');
Also, you have a variable #opportunity in the modal, but it's not defined in your controller, so make sure to define that as well.

Pull post image in rails display in div

i've created a JS grid and i'm trying to pull the logo image and display in div data-thumbnail
How do i add the link to pull post images?
<%- model_class = Post -%>
<div class="spacer spacer-big"></div>
<div class="container" style="padding-right:50px;padding-left:50px;">
<div id="grid">
<div class="box">
<div data-thumbnail= "TRYING TO GET POST LOGO HERE" </div>
I inserted this <%=image_tag post.logoimage.url %> between the quotation marks but i'm still getting an error.
Fix
You'll need to do this:
<%= content_tag :div, "", data: { thumbnail: #post.logoimage.url } %>
Here's info on content_tag for you
This should be accompanied with the following controller action:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
def action
#post = Post.first #-> sets the post object
end
end
--
Data
The error you receive is as follows:
undefined local variable or method `post'
This means your view is calling a non-existent object (variable) (post). The solution to this is to make sure that post is set correctly. And to do this, you need to either use the controller (as per Rails' MVC pattern, or set it in the view:
<% post = Post.first %>
<%= content_tag :div, "", data: { thumbnail: #post.logoimage.url } %>
The problem is that <%- model_class = Post -%> defines model_class as a class, not an object of a class. It should be like <%- model_class = Post.first -%> to get an object.
So you should define your post, that you probably meant by first line. It should be:
<% post = Post.first %>
then you can use this post:
<%=image_tag post.logoimage.url%>
So it is already a tag. You can wrap it in any other.

How to load partial into view when a link is clicked?

I have a list of user 'submissions' in my Rails app, and when a user submission is clicked, I would like the full submission to load into the view, without having to go to a new page.
Here's the code for the list of submissions:
<div id="submission-list-container">
<% current_user.submissions.each do |i| %>
<a href='#'>
<div id="post-container">
<%= i.title %>
</div>
</a>
<% end %>
</div>
The partial I have created, <%= render "show", :submission => i %>,, works fine, but I would like the full submission to be loaded into the view (index.html.erb), when that link above is clicked. Is there a good method for doing this? Should I just do something else like an AJAX call in JavaScript? I like these partials because it feels more clean and organized to seperate code.
My partial is pretty simple at the moment:
<%= submission.title %>
<%= dat_markdown(submission.content) %>
You can do this using a TitlePane in the Dojo Toolkit, and probably there's a similar widget with jQueryUI.
I can only speak to the Dojo Toolkit's version
You would do something like:
<div data-dojo-type="dijit/TitlePane" data-dojo-props="href: '/blah', title: '<%= submission.title %>', open: false">
You can include this in your application layout for lite usage of dojo, loaded from a CDN:
<script data-dojo-config="async: true, parseOnLoad: true"></script>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.9.1/dojo/dojo.js"></script>
The TitlePane is wired up so that when it is expanded, it will autoload the content that is provided to the href parameter.
While this isn't exactly a rails solution directly, it can be used as an alternative.
For a Rails Solution, you can simply use an AJAX call to a controller that renders the partial. You may even be able to hook it up using the
def blah
#submission = Submission.find(...)
respond_to do |format|
format.html # default render
format.js # js behavior
end
end
then a blah.html.erb
<%= render partial: 'submission/submission', object: #submission %>
with the partial
<div id='submission-<%= submission.id %>'>
<div id='submission-<%= submission.id %>-title'><%= link_to(submission.title, 'blah/blah', remote: true) %></div>
<div id='submission-<%= submission.id %>-content'></div>
</div>
and a blah.js.erb
$.get('/submission/content', function(data) { $('#submission-<%= #submission.id %>-content').html(data) } );
and an entry into the submissions_controller with route
def content
#submission = Submission.find(...)
render text: #submission.content
end
This probably isn't an exact solution, but hopefully it'll put you on the right path.

Categories

Resources