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 %>");
Related
My application allows a user to make a list with different categories. While making a list, if the user decides they would like another category, they may create one without leaving the page. The new category will appear in the list, and the user can begin adding items to it.
My issue seems to be that adding any Rails helpers (link_to, render) to my 'new.js.erb' file, it stops the script from doing it's thing. My new div and dropdown menu are not rendered. I get no errors on the console or the server logs. Just nothing. If I remove these methods, everything works fine.
function addCategory(){
var lastCategory = '<%= current_user.categories[-2].name %>';
console.log(lastCategory);
$('#' + lastCategory).after("<h3 class='category'><%= #category.name %></h3>\
<div class='dropdown-button' data-toggle='collapse' data-target='#<%= #category.name %>'>\
<span class='glyphicon glyphicon-chevron-down'></span>\
</div>\
<div id='<%= #category.name %>' class='collapse'>\
<h4>Create a new item here:</h4>\
<div id='append<%= #category.id %>'></div>\
<%= link_to 'Home', root_url %>\ //does not work!
</div>");
}
It's just the link_to and other methods that seem to be causing a problem. All other erb tags <%= %> seem to work and render appropriately.
My goal is to render a form and a link in this newly rendered dropdown section, but since the root of the problem seems to be Rails methods in general, I added a link_to home for clarity.
Damnit, I figured it out. Forget to add 'j' to my rails helpers to convert them to JavaScript
<%= j link_to "Home", root_url %>
I have a form in my Rails 4 app.
I have some jQuery to hide or show form fields based on selections made elsewhere in the form.
This works in development mode, but when I push to production the hidden fields are not shown when the relevant selections are made.
I have a projects form which has:
<%= f.input :ethics_relevance, as: :boolean, boolean_style: :inline, :label => 'Is a research ethics review relevant to or required for this project?' %>
</div>
<div id="project_ethics_relevance_content" class="content hidden">
<div class="row">
<%= f.simple_fields_for :ethics do |f| %>
<%= render 'ethics/ethic_fields', f: f %>
<% end %>
</div>
<div class="row">
<div class="col-md-6">
<%= link_to_add_association 'Add an ethics consideration', f, :ethics, partial: 'ethics/ethic_fields' %>
</div>
</div>
</div>
In my projects.js file, I have:
jQuery(document).ready(function() {
jQuery("#project_ethics_relevance").on('click', function() {
if (jQuery(this)[0].checked) {
jQuery('#project_ethics_relevance_content').removeClass('hidden');
} else {
jQuery('#project_ethics_relevance_content').addClass('hidden');
}
});
});
In development, when the :ethics_relevance boolean is true, the form fields for ethics_fields are displayed.
In production, I check the box, but the form fields do not display. I don't have any related console errors showing in my code inspector.
Can anyone see what might need to be done to get javascript files to work in production mode?
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.
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.
This might be an easy one for you guys, but I'm not sure the best way to achieve it.
Is there some type of .erb I can write that asks "If :notice is present, then render..."?
Here's more about the issue:
My controller specifies a :notice for both the create and update actions (pretty standard). When I load the pages, the notices do as I'd expect and show up. When I reload the page however, (not sure why someone would do this, but I did), the :notice goes away (great, that's what I want), but the containing <div> remains.
How do I go about ensuring that the encapsulating <div> is removed along with the :notice? I'm not sure what conditionals to specify in my view or maybe controller. The view looks something like this (btw, I'm using Twitter Bootstrap JS alerts).
View
<div class="alert-message success fade in" data-alert="alert">
<a class="close" href"#">×</a>
<p><%= notice %></p>
</div>
My controller is a single scaffolded model/resource with basic structure
What I did was:
<% if notice == "[:notice string]" %>
.
.
.
<% end %>
Not sure if this is the most efficient and "Rails-y" way to do it, but it worked for me.