Monday, May 2, 2016

Rails 4 Associations: Help setting up database | Fixed issues

Rails 4 Associations: Help setting up database | Fixed issues


Rails 4 Associations: Help setting up database

Posted: 02 May 2016 06:55 AM PDT

I need some assistance with my Rails 4 associations. I have the following 4 models:

class User < ActiveRecord::Base      has_many :check_ins      has_many :weigh_ins, :through => :check_ins      has_many :repositionings, :through => :check_ins  end    class CheckIn < ActiveRecord::Base      belongs_to :user      has_one :weigh_in      has_one :repositioning  end    class Repositioning < ActiveRecord::Base      # belongs_to :user      belongs_to :check_in  end    class WeighIn < ActiveRecord::Base      # belongs_to :user      belongs_to :check_in  end  

Question: If I am setup this way, how would I input repositionings and weigh_ins separately, but still have them linked through a single check in?

Rails routing sometimes replaces the id in url with id-name. How do I avoid problems?

Posted: 02 May 2016 06:56 AM PDT

Generally the url from my report page looks like this:

 http://test-account.peter:3000/offices/7/reports/index  

However, sometimes it looks like this:

 http://test-account.peter:3000/offices/7-peters-office/reports/index  

Why does this happen?

It was not really a problem until we changed the controller action from a GET to a POST and renamed it. We had to do this so we could pack more parameters in to the ajax request. Users still have this section of the site bookmarked and it throws errors all day long.

I have tried to redirect the route:

   get '/offices/*all/reports/index' => 'offices#show'     get '/offices/:office_id/reports/index' => 'offices#show'     get '/offices/:office_name/reports/index' => 'offices#show'  

Is there a way to catch the name? Or do I have to prevent the name from being added to the url in the first place?

When deploying my Rails 4 application with Capistrano, how to avoid a user timeout error?

Posted: 02 May 2016 06:37 AM PDT

I deploy my project to my production server using the capistrano gem. Everything works fine, however, I've noticed that if my users are accessing the site right when my deployment is trying to wrap things up - they can get an error notice that there was a "timeout" with the server.

How can I handle this so at most is just a little longer of a wait for the user? Currently, in my database.yml config I have the timeout set to: timeout: 5000. Should I just up this to like 15000 ? Or are there some significant downsides to doing that?

Testing whether geocoding happens before_validation

Posted: 02 May 2016 06:25 AM PDT

we're using geocoder gem within a Rails 4.2 Application. Geocoding happens for a places model with address attributes (:street, :postal_code, etc.) using the geocoder gem with nominatim as the API of our choice. Now, I wanted to test whether geocoding is happening accordingly places_controller using Minitest, unfortunately the following problem occurs using a valid (really existing) address

# Test geocoding ability    test 'place address should geocode to lat/lon' do      post :create, place: { name: 'foo',                             street: 'Magdalenenstraße',                             house_number: '17',                             postal_code: '10365',                             city: 'Berlin',                             categories: 'bar' }        new_place = Place.find_by_name('foo')      assert_not_nil new_place.latitude      assert_not_nil new_place.longitude    end  

Within the places model the geocoding is set to before_validation, hence I was expecting that lat/lon is being set (automatically by the gem) before the validation is being applied. Obviously this does not seem to happen as the test fails with undefined method 'latitude' for nil:NilClass (=> post not successfull because no lat/lon has been supplied). Can anyone tell me why and how to solve that problem?

Thanks in advance!

Cloud9 Warning do I just ignore?

Posted: 02 May 2016 06:29 AM PDT

During testing in chapter 3 I get the following warning, is this ok to ignore?

RubyDep: WARNING: your Ruby is outdated/buggy. Please upgrade. (To disable >warnings, set RUBY_DEP_GEM_SILENCE_WARNINGS=1) Run options: --seed 18589

Thanks Gaz Smith

Rails ajax dropdown menu set selected

Posted: 02 May 2016 06:30 AM PDT

I have ajax script which selects necessary data and returns array

server response

[{"id":67,"title":"first","selected":"first"},   {"id":68,"title":"second","selected":"first"},   {"id":69,"title":"third","selected":"first"},    {"id":70,"title":"fourth","selected":"first"}]  

script

$(document).ready ->    category_id = $('#product_category_id').attr('selected', 'selected').val()    product_id = $('#product_id').val()    $.ajax      type: 'GET'      url: "/products/dynamic_admin_subcategory?category_id=#{category_id}&id=#{product_id}"      dataType: 'json'      success: (data) ->        $('#product_subcategory_id').empty()        subcat = $('#product_subcategory_id')        $.each data, (value, key) ->          console.log(key)          $("<option />", {value: key.id, text: key.title}).appendTo(subcat);          $("#product_subcategory_id option:selected").val(key.id).text(key.selected)        return    return  

It works fine, but I cant set selected

Also i have tried

  $("#product_subcategory_id option[value=key.selected]").prop("selected", "selected")  

but cant pass value to option[value=key.selected] What should i do?

use params[:file] as parameter for ActiveJob

Posted: 02 May 2016 06:10 AM PDT

I have a form with a file upload field, which sends a params[:file] when submitted. I want to use this param as a parameter for an job like this:

ImporterJob.perform_later(params[:testrun][:file])  

This however returns an error:

ActiveJob::SerializationError in TestrunsController#create  Unsupported argument type: ActionDispatch::Http::UploadedFile  

Is it possible to send a file parameter to a job?

Ruby on rails - bootstrap material design - Add checkboxes to simple form

Posted: 02 May 2016 06:13 AM PDT

I installed the Bootstrap Material Design in my Ruby on Rails application and every animation is functioning properly, but i can´t see the checkboxes. My code for the checkboxes is:

<div class='form-group'>    <div class='control-label col-sm-2'>    </div>    <div class='col-sm-8'>      <%= f.input :active, :as => :boolean, :label => false, :inline_label => true %>    </div>  </div>  

Can anyone Help me please?

Thank you all!

ActiveRecord single table inheritance - how to get root model?

Posted: 02 May 2016 06:20 AM PDT

I have a model using single table inheritance and a concern that should work on any model.

Consider this example:

class Car    acts_as_categorizable  end    class Suv < Car; end    module Categorizable    def after_safe      siblings = this.class.where(category: self.category)      #... do something with the siblings    end  end  

Now if I have an Suv and manipulate its category, the siblings line will only find the other Suv cars in that category, but I need to find all cars in that category.

I don't want to hardcode this, so given a Suv class, I need to find its root model (Car).

Possible Poltergeist memory leak - how to use session.driver.quit?

Posted: 02 May 2016 05:35 AM PDT

I think I'm running into a memory leak when running Rspec/ Capybara tests. At least, this reasonably high-specced Macbook Pro — and Chrome in particular — slows to an almost unusable crawl when tests are run.

Poltergeist mentions this as a possible issue (I am running JS tests).

The suggested fix is to include session.driver.quit, but where should this be included? Where is session defined by default?

When I include session.driver.quit after tests it causes errors.

Simple form calling undefined url helper when generating a form for a nested resource within a namespace

Posted: 02 May 2016 05:40 AM PDT

Greetings everyone,

I have the following routes:

  namespace :hr do      resources :employees do        resources :skills      end    end  

And the following controllers:

hr/employees_controller.rb
hr/skills.rb

The generated route url helper for an Hr::skill scoped by an Hr::Employee would be:
hr_employee_skill_path(employee_id, skill_id)

However when using simple_form:
simple_form_for [@hr_employee, @hr_skill]
It wrongly uses an undefined URL helper:
hr_employee_hr_skill_path.

I know it's possible to manually set the URL when invoking #simple_form_for, but that would mean the form cannot be fully shared between edit/new views(without any tweaking at least.)

Why is simple form calling undefined URL helpers that way? And what can I do to make it call the right ones properly?

Wait for Ajax call to finish for Capybara

Posted: 02 May 2016 05:11 AM PDT

I am fetching data from a server(via ajax) using 3 select dropdowns. I want to write an integration test where I need to wait for the ajax request to finish then select a value from the next dropdown.

So far I am waiting for some seconds before doing the next select but that's not reliable and not a good solution.

Arel and ActiveRecord's count throws error

Posted: 02 May 2016 04:58 AM PDT

I'm trying implement a library function which should return ActiveRecord relation. Complex SQL query is done with Arel. It has to work on multiple database backends so raw SQL queries are the last resort.

Simplified example:

Spree::Product < ActiveRecord::Base  end    prod_at = Spree::Product.arel_table    # select record's ids by Arel attribute  > Spree::Product.select(prod_at[:id])     Spree::Product Load (0.9ms)  SELECT "spree_products"."id" FROM     "spree_products" WHERE "spree_products"."deleted_at" IS NULL     => #<ActiveRecord::Relation [#<Spree::Product id: 14>, #<Spree…    # previous call converted to SQL, generates correct query  > Spree::Product.select(prod_at[:id]).to_sql    SELECT "spree_products"."id" FROM "spree_products" WHERE    "spree_products"."deleted_at" IS NULL    # Surprisingly, applying ActiveRecord::Calculations.count fails  > Spree::Product.select(prod_at[:id]).count    ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR:  syntax error    at or near "Arel"    LINE 1: SELECT COUNT(#<struct Arel::Attributes::Attribute relation=#...                                ^    : SELECT COUNT(#<struct Arel::Attributes::Attribute relation=#<    Arel::Table:0x00000007553f50 @name="spree_products",    @engine=Spree::Product(id: integer, …  

It looks like .count methods does not unwind embedded Arel expression to SQL and passes it as-is.

Even more surprising, other methods from ActiveRecord::Calculations work correctly, even comparable .calculate :

> Spree::Product.select(prod_at[:id]).calculate(:count, :id)    (0.5ms)  SELECT COUNT("spree_products"."id") FROM "spree_products" WHERE    "spree_products"."deleted_at" IS NULL    => 1253  

Any idea what am I doing wrong ? How adjust Arel object to work also with count method ? Some workaround ?

I have to return ActiveRecord_Relation. The affected count method is called from other 3rd party module which can't be directly modified.

Rails 4 - Custom Validation Error

Posted: 02 May 2016 05:28 AM PDT

This is my model -

class Leave < ActiveRecord::Base  belongs_to :staff  validates :staff, :leave_type, :start_date, :end_date, :number_of_days, :approved_by, presence: true  enum leave_type: {Medical: 0, Annual: 1, Urgent: 3, "Birth Leave": 4}  validate :check_leave, :if => "self.number_of_days.present?"          protected    def check_leave    if self.leave_type = 0      if ( self.number_of_days + LeaveAllocation.last.medical_leave_counter ) > LeaveAllocation.last.medical_leave        self.errors.add(:number_of_days, "Days exceeded the limit")      end    end    if self.leave_type = 1      if ( self.number_of_days + LeaveAllocation.last.annual_leave_counter ) > LeaveAllocation.last.annual_leave        self.errors.add(:number_of_days, "Days exceeded the limit")      end    end    end    end  

When I try to run the validation, it only seems checks the first one "0" even if i change the selection to "1". Any help would be appreciated! Thanks

I have to click confirm around 5 times when i delete something in my Rails app [on hold]

Posted: 02 May 2016 05:20 AM PDT

I have to click 'confirm - yes' around 3-6 times each time i want to delete a note on my notebook application, any ideas why? I have includes a before_action in the controller that includes the destroy function of CRUD:

before_action :find_note, only: [:show, :edit, :update, :destroy]  

Here is the destroy code itself:

def destroy      @note.destroy      redirect_to notes_path  end  

solr sunspot unicode? characters

Posted: 02 May 2016 04:43 AM PDT

How do I use this file provided in sunspot (mapping-ISOLatin1Accent.txt)(or is this the one I need as well)? I need to be able to search for "las pinas" and include results like "las piñas" in my database. Meaning n => ñ? I have my config schema.xml like this for now:

<fieldType name="text" class="solr.TextField" omitNorms="false">    <analyzer>      <charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/>      <tokenizer class="solr.StandardTokenizerFactory"/>      <filter class="solr.StandardFilterFactory"/>      <filter class="solr.LowerCaseFilterFactory"/>      <filter class="solr.PorterStemFilterFactory"/>      <filter class="solr.SynonymFilterFactory" synonyms="synonyms.txt" ignoreCase="true" expand="false" tokenizerFactory="solr.StandardTokenizerFactory"/>    </analyzer>  </fieldType>  

and I have tried moving the <charFilter> setting around as well.

I have also searched and found various solutions mostly pointing to this or this articles but those don't seem to work either.

Cast old string values to datetime with migration in Rails PostgreSQL

Posted: 02 May 2016 06:39 AM PDT

I had a couple of date fields in a database table, however they are firstly initiated as string, not datetime. Therefore, I wanted to change those value types to datetype with a migration,

class ChangeDateColumnsToDateTime < ActiveRecord::Migration    def change      change_column :users, :flight_date_departure, :datetime      change_column :users, :flight_date, :datetime      change_column :users, :appointment_date, :datetime    end  end  

however it can not cast old string values to datetimes that exists in database currently, saying that PG::DatatypeMismatch: ERROR: column "flight_date_departure" cannot be cast automatically to type timestamp without time zone. HINT: You might need to specify "USING flight_date_departure::timestamp without time zone". We've done it without problem in a SQLite database, however there is this problem for PostgreSQL. How can I modify my migration so that I do not lose old values and properly convert them to datetime?

Ajax - Why isn't my remote rails form exucuting create.js.erb?

Posted: 02 May 2016 04:49 AM PDT

I'm getting this error each time i try to post a comment although when I refresh the paage comments are displayed

HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request. (XHR): POST - http://website.com/posts/37/comments

in chrome I got

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

in my comments controller

if @comment.save        respond_to do |format|          format.html do            flash[:success] = 'Comment posted.'          end          format.js # JavaScript response        end      end  

and I set the form to remote: true

so its supposed to execute the code in create.js.erb which is

console.log('working?')  alert('working?')  

commenting is working but the format.js is not

heres the trace

ActionView::Template::Error (undefined local variable or method `comment' for #<#<Class:0x007f3db84dd300>:0x007f3db9aff0e8>  Did you mean?  @comment):      1: console.log('done')      2: alert('done?')      3: //$('comment-<%= comment.parent.id unless comment.parent.blank? %><%= "-".html_safe  unless comment.parent.blank? %><%= comment.id %>').load(location.href + " comment-<%= comment.parent.id unless comment.parent.blank? %><%= "-".html_safe  unless comment.parent.blank? %><%= comment.id %>");      4: //$('comment-<%= comment.parent.id unless comment.parent.blank? %><%= "-".html_safe  unless comment.parent.blank? %><%= comment.id %>').html('<% j (render 'comments') %>')      5: //console.log(comment.parent.id unless comment.parent.blank? %><%= "-".html_safe  unless comment.parent.blank? %><%= comment.id %>)    app/views/comments/create.js.erb:3:in `_app_views_comments_create_js_erb___4383133957853497951_69951529166680'    app/controllers/comments_controller.rb:21:in `create'        Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (3.8ms)    Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.4ms)    Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-4.2.5/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb (72.2ms)  

Matching Signed Headers Encrypted in Ruby on Rails and JavaScript

Posted: 02 May 2016 03:59 AM PDT

I am using ApiAuth gem (as found here) to sign my request. I am also writing my own JavaScript code using CryptoJS (as found here) to provide authentication by checking the encrypted header generated by ApiAuth against the one generated by my code.

Given below is a code snippet from ApiAuth Gem:

def hmac_signature(headers, secret_key, options)    if options[:with_http_method]      canonical_string = headers.canonical_string_with_http_method(options[:override_http_method])    else      canonical_string = headers.canonical_string    end    digest = OpenSSL::Digest.new('sha1')    b64_encode(OpenSSL::HMAC.digest(digest, secret_key, canonical_string))  end  

Here is the code I have written as an equivalent in JavaScript:

function hmacSignature(request, appSecret) {   return CryptoJS.HmacSHA(canonicalString(request), appSecret).toString(CryptoJS.enc.Base64);}  

These two don't generate the same encrypted header. I tried using jsSHA to do the same thing and while the encrypted header generated by jsSHA and CryptoJS is the same, they don't match the one generated by ApiAuth.

Kindly help me figure out how to make this work.

Pass data to modal

Posted: 02 May 2016 04:02 AM PDT

Sorry for that question, googled a lot.. but I cant find a solution.. I am using materialize css (not twitter) and want to pass an ID in a modal

HTML

<%= link_to 'Modal', '#modal3', :data => {:toggle => 'modal', :data_id => '123'}, :class=> 'modal-trigger' %>  

COFFEE

$('.modal-trigger').leanModal()   ready: ->    $("#canvas").load($(this).data('id'))    return  

In Modal

<div id="canvas" ></div>   

Thanks for helping..

ruby on rails braintree fail on duplicate payment method

Posted: 02 May 2016 03:51 AM PDT

i am trying to implement braintree payments into a ruby app, and everything seems to be working fine, but when i pass fail_on_duplicate_payment_method_card as an option i am getting invalid keys: options[fail_on_duplicate_payment_method_card]

result = Braintree::PaymentMethod.create(          :customer_id => current_user.customer_cim_id,          :payment_method_nonce => 'fake-valid-amex-nonce',          :cardholder_name => "#{current_user.first_name} #{current_user.last_name}",          :options => {              :make_default => true,              :fail_on_duplicate_payment_method_card => true          }      )      if result.success?        customer = Braintree::Customer.find(current_user.customer_cim_id)        puts customer.id        puts customer.payment_methods[0].token      else        p result.errors      end  

Ruby on Rails server requirements

Posted: 02 May 2016 06:31 AM PDT

I use rails for small applications, but I'm not at all an expert. I'm hosting them on a Digital Ocean server with 512MB ram, which seems to be insufficient.

I was wondering what are Ruby on Rails server requirements (in terms of RAM) for a single app.

Besides I can I measure if my server is able to support the number of application on my server?

Many thanks

ActionView::Template::Error (singleton can't be dumped)

Posted: 02 May 2016 05:10 AM PDT

I am using gem 'jbuilder_cache_multi' for cache my json responses. I am encountering a strange error when i hit my api from my ios native app. Below is the error i got:

ActionView::Template::Error (singleton can't be dumped):  2:  3: json.orders do  4:   json.cache! ['v1', I18n.locale, @orders] do  5:     json.cache_collection! @orders, key: ['v1', I18n.locale] do |order|  6:       json.partial! 'order', order: order  7:     end  8:   end    app/views/api/v1/orders/index.json.jbuilder:5:in `block (2 levels) in   

Request is:

Started GET "/api/v1/orders?page=2&q%5Bmerchant_id_eq%5D=1&q%5Bs%5D=created_at+asc&q%5Bstate_not_in%5D%5B%5D=composing&q%5Bstate_not_in%5D%5B%5D=distributed&q%5Bstate_not_in%5D%5B%5D=canceled"   

Can anyone help in this regard. Thanks

Ruby on Rails 4/ Turbolinks - how to disable turbolinks on a Rails UJS (ajax xhr) call

Posted: 02 May 2016 04:41 AM PDT

On a Deal page, I have a Rails UJS call. It loads a modal. The problem is the following:

  • I am on the homepage with a list of deals

  • I then click on a Deal n°4

  • I arrive on the Deal n°4 page

  • I click the button that point to a modal (here using Rails UJS)

  • The modal appears

  • I press chrome "back" button which makes me go back to the homepage

  • I reclick on the link "Deal n°4" to go back to the Deal page n°4

  • I arrive on the Deal page n°4

  • and here is the problem: when I click again the button that should trigger the modal to appear , the modal DOES NOT appear.

I am 100% sure it's due to turbolinks as I removed it and then it works.

I want to keep generally turbolinks but to disable it only for this AJAX call.

I read all i can think of on SO and the web but nothing works.

CODE

(note: on the hompeage: just the list of the deals and I can click on a deal- it's a standard link)

Deal page

html

<div id="modal-zone">          <div class="insider">        <span>          <%= link_to image_tag(smallest_src_request),                modal_path,                remote: true,                class: "link",                alt: "loadin'" %>        </span>      </div>    </div>  

When the user clicks the Rails UJS link, it points to views/modal.js.erb (I am using hubspot Messenger also as below)

var msg;  msg = Messenger().post({    message:  'This is your participation number X to the deal',      hideAfter:  false    });   

In terms of html, this modal is:

<ul class="messenger messenger-fixed messenger-on-bottom messenger-theme-flat">    <li class="messenger-message-slot messenger-shown messenger-first messenger-last">      <div class="messenger-message message alert error message-error alert-error">        <div class="messenger-message-inner">This is your participation number X to the deal  <br>        </div>      </div>    </li>  </ul>  

I tried adding directly of via a jquery injection data-no-turbolink to those different places and it never worked

on the main link_to with the Rails UJS

<%= link_to image_tag(smallest_src_request),                modal_path,                remote: true,                data: { no_turbolink: true } " %>  

or even on the parent div of the modal:

<ul class="messenger messenger-fixed messenger-on-bottom messenger-theme-flat" data-no-turbolink: "true">  

But nothing worked.

I feel what the techniques I tried using are only working when you want to disable turbolinks on a on page:load, or page:change but not when you need to disable it ON the elements that are loaded on an event I don't actually know the name but which is kind of "page:ajaxcall", that is to say on the content loaded by an ajax call by Rails UJS.

NGINX Config: How to match any filetype or subfolder of given path?

Posted: 02 May 2016 05:30 AM PDT

I need to bypass rails via NGINX for any requests that fall beneath a certain path for various assets such as:

test.com/inc/js/test.js     -> /var/www/test/public/example/inc/js/test.js    test.com/inc/js/another/subfolder/test.js     -> /var/www/test/public/example/inc/js/another/subfolder/test.js    test.com/inc/css/test.css     -> /var/www/test/public/example/inc/css/test.css    test.com/inc/css/any/given/subfolders/test.css     -> /var/www/test/public/example/inc/css/any/given/subfolders/test.css  

I am currently trying to edit the nginx config such that any web request maps to the appropriate file:

location ~* /inc {      root /var/www/test/public/example/inc;      try_files $uri =404;  }  

Which isn't working - I assumed that any request of /inc would then map accordingly, but I am clearly missing something? How can I map any requests to /inc to the correct corresponding path?

Deploy ActionCable on Heroku (Rails 5 beta4)

Posted: 02 May 2016 03:40 AM PDT

I have a working rails 5 app with ActionCable on my localhost, and I'm trying to deploy it to heroku. When accessing the page where the chat room is, I can see in chrome's console:

WebSocket connection to 'wss://full-beyond-9816.herokuapp.com/cable' failed: Error during WebSocket handshake: Unexpected response code: 404  

I did setup Redis and the Redis addon on heroku. Here is the production part of my cable.yml file:

production: &production    :url: redis://redistogo:4140ce7f3e7493bd1b12@porgy.redistogo.com:9463/    :host: tarpon.redistogo.com    :port: 10272    :password: 12e348ac10ca002879ce7d85daf0bb0    :inline: true    :timeout: 1  

Here is my room.coffee file:

(function() {    this.App || (this.App = {});      App.cable = ActionCable.createConsumer();    }).call(this);  

Setting up ActionCable on heroku seems tricky, and every post I've found on the subject is either using Phusion Passenger (I'm using Puma), or with a pretty old version of ActionCable (I'm using the latest beta of Rails 5).

How should I set this up ? Thanks for your time and help

Rails: Validates greater_than_or_equal_to 0 does not work

Posted: 02 May 2016 03:47 AM PDT

I shouldn't be able to set user.fee_email = -1 but I can, even though I've specified in my model that the numericality of fee_email should be positive.

Given:

class User < ActiveRecord::Base    validates :fee_email, numericality: { greater_than_or_equal_to: 0 }  ...  end  

This should not happen:

2.2.1 :002 > a = User.first  2.2.1 :003 > a.fee_email   => #<BigDecimal:43cbbe0,'0.0',9(27)>   2.2.1 :004 > a.fee_email = -1   => -1   2.2.1 :005 > a.fee_email   => #<BigDecimal:43b5688,'-0.1E1',9(27)>   

Devise email templates [on hold]

Posted: 02 May 2016 05:15 AM PDT

I'm working with Devise in Ruby on Rails and I want to change defaul Devise email templates. I can't find .css files for email templates. Where should I put .css files for email templates?

Handling Confirmations of link by Custom Jquery Dialog in Rails

Posted: 02 May 2016 05:49 AM PDT

I needed a custom pop-up dialog in order to replace the default browser option for data-confirmation. There were a lot of example online for data-confirmation for method: delete, however I needed to make minor customization to make it work for normal links as well.

For example there are the 2 types of links I would render a dialog for:

<%= link_to(scoreboard_team_path(@scoreboard, team), remote: true, method: :delete, data: {confirm: "Are you sure you want to delete?"})%>     <%= link_to "Clear Teams", deleteteams_scoreboard_path(@scoreboard), class: "btn btn-primary reset-link", :data => {:confirm => "Are you absolutely sure you want to delete all teams?"} %>  

With the information I have researched online, I have come up with the following jquery code for app-wide confirmation for these types of links:

$(document).ready(function(){        $.rails.allowAction = function(link) {            if (!link.attr('data-confirm')) {              return true;            }            $.rails.showConfirmDialog(link);            return false;      };        $.rails.confirmed = function(link) {        link.removeAttr('data-confirm');        if(link.hasClass("reset-link")){           window.location.replace("" + link.context.href + "");        } else {            return link.trigger('click.rails');        }        };           $.rails.showConfirmDialog = function(link) {            var html;            var message = link.data("confirm");            html = "<div id=\"dialog-confirm\" title=\"Warning!\">\n  <p>"+message+"</p>\n</div>";            return $(html).dialog({              resizable: false,              modal: true,              buttons: {                OK: function() {                  $.rails.confirmed(link);                  return $(this).dialog("close");                },                Cancel: function() {                  return $(this).dialog("close");                }              }            });        };  });  

My problem is that the authors of the articles don't explain well about what is happening.

So therefore my questions are:

What does the following code mean:

if (!link.attr('data-confirm')) {              return true;            }  

In the line window.location.replace("" + link.context.href + ""); what does link.context.href mean?

Dotenv not availabe in routes.rb?

Posted: 02 May 2016 03:22 AM PDT

eversince I started using Dotenv inside my routes.rb I get weird errors.

I'm using gem 'dotenv-rails', '~> 2.0.0'

routes.rb:

constraints(host: ENV.fetch("SHORTENER_DOMAIN")) do    get ':id', to: 'shortener#redirect'  end  

Terminal:

username:~/Sites/my_app$ rails s  /Users/username/Sites/my_app/config/routes.rb:4:in 'fetch': key not found: "SHORTENER_DOMAIN" (KeyError)      from /Users/username/Sites/my_app/config/routes.rb:4:in 'block in <top (required)>'    username:~/Sites/my_app$ rails s  => Booting Thin  => Rails 4.2.5 application starting in development on http://localhost:3000  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server  Thin web server (v1.6.4 codename Gob Bluth)  Maximum connections set to 1024  Listening on localhost:3000, CTRL+C to stop  

I did not do anything between these two rails s, just repeated it and it worked. It's really strange.

Anyone knows what's happening?

1 comment:

  1. Many thanks for your kind invitation. I’ll join you.
    Would you like to play cards?
    Come to the party with me, please.
    See you soon...

    เล่นบาคาร่า

    คาสิโน

    คาสิโนออนไลน์

    คาสิโน

    ReplyDelete