Wednesday, December 21, 2016

How to return from a Rails rack call? | Fixed issues

How to return from a Rails rack call? | Fixed issues


How to return from a Rails rack call?

Posted: 21 Dec 2016 07:49 AM PST

I am using Faye websocket implementation. When a websocket is detected I want to make sure the user sent a given header before I open the connection, or else I want to return an error. I tried returning error 401 using [] but I keep oberving that the code continues execution and the websocket is created anyway. I managed to prevent it by adding return after it, but I am not sure this is the right way. On the client side I am implementing it in python using ws4py and when I return I get an exception raised indicating it received a 302 code, not the 401 I was expecting to send.

My ruby code (without the websocket events code) follows:

  App = lambda do |env|      if Faye::WebSocket.websocket?(env)        unless env['HTTP_MY_HEADER']          [401, {'Content-Type' => 'application/json'}, '{"message": "I was expecting a header here"}']          #return (??)        end          ws = Faye::WebSocket.new(env)        # Rest of websocket call handling      else        # Normal HTTP request        [200, {'Content-Type' => 'text/plain'}, ['Hello']]      end    end  

Rails, add a trigger to update more than one column

Posted: 21 Dec 2016 07:43 AM PST

[Following this guide here,][1] I want to add a trigger, that updates more than one attribute of a model. Here is what I have now:

class AddTriggerToArguments < ActiveRecord::Migration[5.0]      def up      execute %{      CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE    ON arguments FOR EACH ROW EXECUTE PROCEDURE    tsvector_update_trigger(tsv_body, 'pg_catalog.simple', description);   }    end      def down      execute %{DROP TRIGGER tsvectorupdate ON arguments}      end  end  

As you can see in the line

tsvector_update_trigger(tsv_body, 'pg_catalog.simple', description);  

updates the description attribute. But what do I have to do, so that multiple attributes will be updated?

My model has title and description as attributes. I want to add title to the trigger. I tried this, but it didnt work:

  def up      execute %{      CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE    ON arguments FOR EACH ROW EXECUTE PROCEDURE    tsvector_update_trigger(tsv_body, 'pg_catalog.simple', description)    tsvector_update_trigger(tsv_body, 'pg_catalog.simple', title);       }     end  

But that didn't work. Can anyone help me?

What websock library does action cable use?

Posted: 21 Dec 2016 07:35 AM PST

Does Rails action cable use a custom websocket library or does it use an open source one?

Before process_action callback :authenticate_user! has not been defined

Posted: 21 Dec 2016 07:46 AM PST

I'm creating a rails app that includes devise. I'm trying to add Twilio messaging to my site with Ngrok, i used this tutorial: https://www.twilio.com/blog/2016/04/receive-and-reply-to-sms-in-rails.html

I was able to open Ngrok in the console and get the web-id they give for my url. I keep getting this error when I plug the url into my browser ..I'm supposed to get to my own rails local app. Not sure whats wrong.

What I added in my messaging controller made for ngrok:

class MessagesController < ApplicationController skip_before_filter :verify_authenticity_token skip_before_filter :authenticate_user!, :only => "reply" def reply message_body = params["Body"] from_number = params["From"] boot_twilio sms = @client.messages.create( from: Rails.application.secrets.twilio_number, to: from_number, body: "Hello there, thanks for texting me. Your number is #{from_number}." ) #twilio expects a HTTP response to this request end

private def boot_twilio account_sid = Rails.application.secrets.twilio_sid auth_token = Rails.application.secrets.twilio_token @client = Twilio::REST::Client.new account_sid, auth_token end end really unsure what is wrong. when its not connecting to the 'def reply' and authenticate_user should be defined by devise.

Fog Gem - Access Denied on deleting S3 file

Posted: 21 Dec 2016 07:04 AM PST

I'm using fog gem with carrierwave for uploading files to s3. The upload is ok and works perfectly, but, once I try to delete some instance of my model with the file attached, it sends the delete request and returns Access Denied, as bellow:

[fog][WARNING] fog: followed redirect to bucket-name.s3-us-west-2.amazonaws.com, connecting to the matching region will be more performant  Excon::Error::Forbidden: Expected(204) <=> Actual(403 Forbidden)  excon.error.response    :body          => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>EB625F4C97AD368E</RequestId><HostId>E+We/GvBslMHoNn9nTT6Uw3t0qfJ9jXHCNkJRu0KOk5sk8WoFZbkaIyUB0WcWNPZuH2uCeoZTIo=</HostId></Error>"    :cookies       => [    ]    :headers       => {      "Content-Type"     => "application/xml"      "Date"             => "Wed, 21 Dec 2016 14:48:53 GMT"      "Server"           => "AmazonS3"      "x-amz-id-2"       => "E+We/GvBslMHoNn9nTT6Uw3t0qfJ9jXHCNkJRu0KOk5sk8WoFZbkaIyUB0WcWNPZuH2uCeoZTIo="      "x-amz-request-id" => "EB625F4C97AD368E"    }    :host          => "bucket-name.s3.amazonaws.com"    :local_address => "192.168.2.106"    :local_port    => 51425    :path          => "/uploads/conta/pdf_conta/375/1530_09-2016.pdf"    :port          => 443    :reason_phrase => "Forbidden"    :remote_ip     => "52.216.66.16"    :status        => 403    :status_line   => "HTTP/1.1 403 Forbidden\r\n"        from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/expects.rb:7:in `response_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/response_parser.rb:9:in `response_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/connection.rb:388:in `response'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/connection.rb:252:in `request'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/idempotent.rb:27:in `error_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/base.rb:11:in `error_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/base.rb:11:in `error_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/connection.rb:272:in `rescue in request'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/connection.rb:215:in `request'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/idempotent.rb:27:in `error_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/base.rb:11:in `error_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/base.rb:11:in `error_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/connection.rb:272:in `rescue in request'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/connection.rb:215:in `request'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/idempotent.rb:27:in `error_call'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/excon-0.54.0/lib/excon/middlewares/base.rb:11:in `error_call'  ... 36 levels...      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in `start'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:in `console'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `block in require'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require'      from /home/ronanlopes/HY Brazil/HyBrazil/bin/rails:9:in `<top (required)>'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `block in load'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'      from /home/ronanlopes/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:287:in `load'      from /home/ronanlopes/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /home/ronanlopes/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from -e:1:in `<main>'  

The user token I'm using on my config has the AmazonS3FullAccess - AWS Managed policy, so it doesn't makes sense to me. Any ideas?

PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

Posted: 21 Dec 2016 06:53 AM PST

Im having an issue in production with Postgres sql with a distinct, order by restrictions. Looking at similar issues I do not seem to find the distinct order by conflict.

I am displaying all reports for a current user order by date desc. I then created filters so that users can filter on specific attributes in the report. Within the filter selects i used DISTINCT to display only the uniq values. The following two attributes "target_species" and "tide" are creating the

Is the conflict because i am displaying all reports order by date DESC, and then utilizing DISTINCT separately in the filters?

reports_controller.rb

    def index        @reports = current_user.reports.order("date DESC")        @reports_for_filter = @reports.select("DISTINCT(target_species)")        @reports_for_filter_tide = @reports.select("DISTINCT(tide)")      end        def filter        @target_species = params[:target_species] unless params[:target_species].blank?        @tide = params[:tide] unless params[:tide].blank?        # for uniq        @reports = current_user.reports.order("date DESC")        @reports_for_filter = @reports.select("DISTINCT(target_species)") #sets up target_species for filter box        @reports_for_filter_tide = @reports.select("DISTINCT(tide)")          @reports = @reports.selected_species(@target_species) if @target_species        @reports = @reports.selected_tide(@tide) if @tide        end  

reports view index.html.erb

    <div class="col-sm-3">        <label>Species</label><br>        <select id="target_species" name="target_species" class="form-control m-b">               <option value="">Select Species</option>              <% @reports_for_filter.each do |report| %>              <% puts "target species is #{report.target_species}".green %>            <option value="<%= report.target_species %>"><%= report.target_species %>            </option>              <% end %>        </select>      </div>      <div class="col-sm-3">        <label>Tide</label><br>          <select id="tide" name="tide" class="form-control m-b">               <option value="">Select Tide</option>              <% @reports_for_filter_tide.each do |report| %>            <option value="<%= report.tide %>" <%= selected_tide(report.tide) %>><%= report.tide %>            </option>              <% end %>          </select>      </div>        <script>        $('#target_species').change(function(){          $('#filter_form').submit();        });         $('#tide').change(function(){          $('#filter_form').submit();        });      </script>  

report.rb

belongs_to :location belongs_to :user

    scope :selected_species, -> (the_species) { where(target_species: the_species)}        scope :selected_tide, -> (the_tide) {where(tide: the_tide)}  

How can i do this with friendly on rails 5

Posted: 21 Dec 2016 06:53 AM PST

how can you do this with friendly in rails 5

www.example.com/view/twd/1-0

www.example.com/view/ahs/1-0

I tried everything but when I put a second 1.00 it creates it so 1-0 + random code

thanks for your help :D

Star rating system in rails

Posted: 21 Dec 2016 06:42 AM PST

In my project I want to use a rating system http://www.jqueryrain.com/?SGgGB_oZ I have successfully added it to my project, and it works. I have 2 models: Casino & Rating. Casino has_many :ratings, and Rating belongs_to :casino. On my casino index page I want to display the rating system for each casino. This is my view:

<h1>List of casinos</h1>    <div class="casinos-list">    <% @casinos.each do |casino| %>      <div class="casino-item">        <p class="casino-name"><%= link_to casino.name, casino %></p>        <p class="casino-description"><%= casino.description %></p>        <ul class="rating">          <% form_id = "casino_#{casino.id}_rating" %>          <%= form_for casino.ratings.last || casino.ratings.build, html:              { id: "casino_#{casino.id}_rating", class: 'star_rating_form' } do |f| %>            <%= f.hidden_field :casino_id %>            <%= f.hidden_field :score, id: "#{form_id}_stars", class: 'star-value' %>          <% end %>          </ul>        <div id="<%= "average_rating_#{form_id}" %>"><%= casino.average_rating.to_f %></div>        <div id="<%= "rate_#{casino.id}" %>" class="rateit" data-rateit-mode="font">        </div>      </div>    <% end %>  </div>  

My application.js:

$(document).on('turbolinks:load', function () {      $('.rateit-reset').remove();      $('.rateit-hover').click(function () {      var rating = $(this).parents().attr('aria-valuenow');      var float_number = parseFloat(rating);      var rating_form_input = $(this).parents().parents('.casino-item').children('.rating').children('.star_rating_form').children('.star-value');      var form_id = $(this).parents().parents('.casino-item').children('.rating').children('.star_rating_form').attr('id');      rating_form_input.val(float_number);        $.ajax({        type: 'post',        url: $('#' + form_id).attr('action'),        data: $('#' + form_id).serialize()      });    });    });  

And it works, saving the proper value to db, but, as you can see, I use here form_for casino.ratings.last. I need to add a new rating to the array of ratings, but not to change the last one. Any ideas how should I do it? Thanks.

Setting up the cloudfront CDN for rails

Posted: 21 Dec 2016 06:10 AM PST

I setting up the cloudfront CDN for rails but its not working.

My site is on ec2.

I do following steps.

For https://console.aws.amazon.com/cloudfront

  1. Create Distributions
  2. Add ec2 URL in the Origin Domain Name
  3. Submit the distributions and It's display me below (See attachment)

enter image description here

For Ruby on Rails side

  1. In production.rb file, I added below line

    config.action_controller.asset_host = "CDN-DOMAIN-NAME.cloudfront.net"

  2. Restart the application and Testing.

But it's not working. When I open CDN url in another tab then it's redirect to my ec2 URL site. I think that is the problem. So can any one help me what's the problem and why it's redirect to my ec2 URL site?

HAML: How do I generate a self-closing (href-lang) link tag?

Posted: 21 Dec 2016 06:01 AM PST

I need to generate this exact (href-lang) link HAML:

<link rel="alternate" hreflang="es" href="http://es.example.com/" />  

This HAML code:

%link{href: "http://es.example.com/", hreflang: "es", rel: "alternate"}  

gets converted to:

<link href="http://es.example.com/" hreflang="es" rel="alternate"></link>  

Any ideas anyone?

Click on a link and go to another element on the same page

Posted: 21 Dec 2016 05:58 AM PST

I have

  <button>  <a href="#x">More</a> </button>  

and I have <div id="x"> </div>

But when I click on link, my page before going to desired div reloads(

I can't reproduce this behaviour on jsfiddle because there it works fine. Can this be because I am using rails an turned turbolinks off? If you need I can deploy the code to the server but I haven't done this yet.

Type error for implicit conversion while working with API and JSON data in rails 4

Posted: 21 Dec 2016 05:09 AM PST

I making a post request through postman with the following JSON code:

 {   "order":   {       "txnid":"SA",       "stamp_amount": "200",       "service": {                      "name": "Affidavit"                  },       "payment": {                  "created_at": {                                  "strftime": "12-6-2016"                                },                   "mode": "Cash"                  },      "user": {                  "profile": {                                  "first_name": "Mahesh",                                   "country": {                                                  "phone_code":"080"                                              }                              },                   "phone":"9988998899"              },       "address":{                      "address1":"dadacsa",                      "address2":"ca",                       "locality":{                                      "name":"asca"                                  },                       "landmark":"asca",                       "city":{                                  "name":"aacs", "state":{                                                              "name":"asca"                                                          }                              }                  },       "product":"asx",       "total_amount":"5000",       "document":{                      "default_price":"100"                  },       "delivery_amount":"99",       "discount":"0"      },    "no_of_copies":"1"   }  

As I make request to my invoice_api_controller with the following:

 def order_invoice          response = Hash.new          result = Hash.new          if params[:order] && params[:order][:txnid] && params[:no_of_copies] && params[:order][:total_amount]!= 0              @order = JSON.parse(params[:order]).each do |order|                  @order['stamp_amount'] = order['stamp_amount'] || ''                  @order['txnid'] = order['txnid']                  @order['service']['name'] = order['service']['name'] || ''                  @order['payment']['created_at']['strftime'] = order['payment']                  ['created_at']['strftime']                  @order['payment']['mode'] = order['payment']['mode'] || ''                  @order['user']['name'] = order['user']['name']                  @order['user']['profile']['first_name'] = order['user']                  ['profile']['first_name'] || ''                  @order['address']['address1'] = order['address']['address1']                   || ''                   @order['address']['address2'] = order['address']['address2']                   || ''                  @order['address']['locality']['name'] = order['address']                  ['locality']['name'] || ''                  @order['address']['landmark'] = order['address']['landmark']                   || ''                  @order['address']['city']['name'] = order['address']['city']                  ['name'] || ''                   @order['address']['city']['state']['name'] = order['address']                  ['city']['state']['name'] || ''                  @order['user']['profile']['country']['phone_code'] = ['user']                  ['profile']['country']['phone_code'] || ''                  @order['user']['phone'] = order['user']['phone'] || ''                  @order['product'] = order['product'] || ''                  @order['total_amount'] = order['total_amount']                  @order['document']['default_price'] = order['document']                  ['default_price'] || ''                  @order['delivery_amount'] =  order['delivery_amount'] || ''                  @order['discount'] =  order['discount'] || ''                  @no_of_copies = params[:no_of_copies]              end              response.merge! ApiStatusList::OK          else              response.merge! ApiStatusList::INVALID_REQUEST          end           render :json => response      end  

It throws the following error no implicit conversion of ActionController::Parameters into String for the line @order = JSON.parse(params[:order]).each do |order|

I am not sure what am I doing wrong for I am new to working with Rails and APi's.Please help with detailed elaboration.It would help a great deal

Ruby on Rails - chat with Devise and ActionCable

Posted: 21 Dec 2016 05:53 AM PST

I follow a tutorial: https://www.sitepoint.com/create-a-chat-app-with-rails-5-actioncable-and-devise/

I want to create an app with ActionCable. App works, but new messages are visible only after refreshing the page.

Coffee script responsible for sending message to chat:

jQuery(document).on 'turbolinks:load', ->    messages = $('#messages')    if $('#messages').length > 0      messages_to_bottom = -> messages.scrollTop(messages.prop("scrollHeight"))        messages_to_bottom()        App.global_chat = App.cable.subscriptions.create {          channel: "ChatRoomsChannel"          chat_room_id: messages.data('chat-room-id')        },        connected: ->          # Called when the subscription is ready for use on the server          disconnected: ->          # Called when the subscription has been terminated by the server          received: (data) ->          messages.append data['message']          messages_to_bottom()          send_message: (message, chat_room_id) ->          @perform 'send_message', message: message, chat_room_id: chat_room_id          $('#new_message').submit (e) ->        $this = $(this)        textarea = $this.find('#message_body')        if $.trim(textarea.val()).length > 1          App.global_chat.send_message textarea.val(), messages.data('chat-room-id')          textarea.val('')        e.preventDefault()        return false  

I have Redis installed on my Ubuntu. Rails console doesn't give me any errors.

ArgumentError:wrong number of arguments (1 for 0) [on hold]

Posted: 21 Dec 2016 07:47 AM PST

So how we resolve the error in initialize function,Which thing need to be done to remove this error

Here is the Factories/user.rb

FactoryGirl.define do    factory :user do |u|      u.first_name Faker::Name.first_name      u.last_name Faker::Name.last_name      u.email Faker::Internet.email      u.username Faker::Name.name      u.title Faker::Name.title      u.password "hellohello"      u.password_confirmation "hellohello"   end  end  

Here is the mode spec model/user_spec.rb

require 'rails_helper'    RSpec.describe User, :type => :model do      user = ''    describe "create" do      user = FactoryGirl.create(:user)    end    #describe "validations"    describe "Count all the user" do      it "should have one item created before being created" do        #binding.pry        expect(User.all.count).to eq(1)      end   end  end   

When testing the model user_spec.rb model it gives the error: enter image description here

Rails : get json value in hidden_field form (giphy api)

Posted: 21 Dec 2016 05:52 AM PST

I am using the Giphy search API to let my users search for gifs and let them add gif.

Here is simplified part of my code to make it works :

_Form.html.erb

<%= form_for Task.new do |f| %>  <%= f.hidden_field :gif, id: "GifUrl", value: "" %>  <input type="text" name="search" placeholder="Search gif">  <!-- This part render the gif search result -->  <div id="score"></div>  <% end %>  

Part of my script where I fetch the details of the gif from giphy

  this.displayResult = function(url) {      const target = document.getElementById('score');      const img = document.createElement('img');      img.src = url;        target.appendChild(img);    }  

What I wanted to do is to scrape the html src value of the gif link returned and pass it in my form through an hidden_field, but it returns : [object Object] as a value, instead of the proper gif link.

 => #<Task id: 285, description: "", user_id: 37, gif: "[object Object]">  

Should I use an html parser like nokogiri or am I doing something wrong ? How can achieve this ?

Thanks !

How can i add scoped_collection for active admin register page?

Posted: 21 Dec 2016 04:20 AM PST

Something like that in my ActiveAdmin "Leads" page :

 ActiveAdmin.register_page "Leads" do         ......           scope_to :to_be_contacted         ......        controller do          def scoped_collection            Call.to_be_contacted          end        end      end  

One Model and two controller validation Ruby on Rails?

Posted: 21 Dec 2016 04:46 AM PST

One thing that confuses me the most is when doing validation in one model with two controllers. I have a login system which register and logs users in. There both use the same model but both does not use the same amount of HTML widgets. One controller contains password, retype password, user name, first & second name and so on. The second controller uses only the user name and password fields. How would you do validation in the same model for this situation?

Thank you

here is the controller that register new users:

class UsersController < ApplicationController    def new      @user = User.new    end      def create      @user = User.new(user_params)        if @user.save        session[:user_id] = @user.id        redirect_to '/cool'      else        @user = Newuser.new        @user.valid?         @user.errors.messages        render 'new'      end    end      private      def user_params      params.require(:user).permit(:name, :email, :password, :salt, :firstname,      :secondname, :address, :postcode)    end  end  

second controller:

class LoginsController < ApplicationController    before_filter :authorize      def index      @rentals = Rental.where(user_id: current_user.id).limit(5)      @buys = Buy.where(user_id: current_user.id).limit(5)      @users = User.where(id: current_user.id)      @buyGames = BuyGame.where(user_id: current_user.id).limit(5)    end       def destroy      @user = User.find(params[:id])      @user.destroy      redirect_to '/logout'    end      def edit      @user = User.find(params[:id])    end      def update      @user = User.find(params[:id])        if @user.update(account_params)        redirect_to '/cool'      else        render 'edit'      end    end      private      def account_params      params.require(:user).permit(:name, :email, :password, :salt, :firstname, :secondname, :address, :postcode)    end  end  

Here is my model:

class User < ApplicationRecord    has_secure_password  end  

facebook login error: URL Blocked: This redirect failed because the redirect URI is not whitelisted

Posted: 21 Dec 2016 04:07 AM PST

In my rails app i have added facebook login using Omniauth I created my app and everything was good on localhost but then i added my url on Valid OAuth redirect URIs and started getting this error:

URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app's Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.  

My valid outh redirect url is: http://www.greyshift.co/profiles/new

My domain name is: www.greyshift.co My site url is: http://www.greyshift.co/

How to integrate Angular 2 in Rails

Posted: 21 Dec 2016 05:39 AM PST

I have web application developed on Rails and I want to integrate Angular 2 so that I can re use some functionality in Rails. How can I render my Angular components inside my rails views?

Rails - Current_user is nil when delete a Pain

Posted: 21 Dec 2016 05:40 AM PST

I'm using Public Activity to get notifications. I'm tracking the new prayers in my Prayer model. For some reason current_user is nil when i deleted a Pain and i don't understand why.

class Prayer < ApplicationRecord   include PublicActivity::Model      has_many :activities, as: :trackable, class_name: 'PublicActivity::Activity', dependent: :destroy    tracked owner: Proc.new { |controller, model| controller.current_user } #fail current_user is nil  end    class Pain < ApplicationRecord   belongs_to :user   has_many :prayers, dependent: :destroy  end  

I can provide more code, but I'm not sure what would be useful. Thanks a lot

Edit: I forgot to say that i'm trying to delete the Pain in the Rails admin page

Edit2 : Rails admin config

RailsAdmin.config do |config|     config.actions do    dashboard                     # mandatory    index                         # mandatory    new    export    bulk_delete    show    edit    delete    show_in_app   end     config.authorize_with do |controller|    redirect_to main_app.root_path unless current_user &&    current_user.admin   end  end  

adsense rubyonrails 5 project

Posted: 21 Dec 2016 04:11 AM PST

I've spent the past month trying to get ads on my web app to just be told by a guy in a google forum that Adsense doesn't work with apps.

Is this true? Sounds strange. I couldn't find a convincing answer one way or another.

If Adsense doesn't work on Ruby on Rails 5 how can I easily get ads on my app? Is there a gem? I feel like this would be a common question, but I couldn't get it answered in my google searches so I've come to you SO.

Please help!

Please checkout www.eduly.in and go inspect element to see error

https://i.stack.imgur.com/ybC8r.png

How to make an ajax request in ruby on rails?

Posted: 21 Dec 2016 06:32 AM PST

Hello I am new to ruby on rails I have just started to learn. I would like to know how can I make the ajax request. My js code:

$(document).ready(function(){    $(".form_submit").click(function() {           var apiid = $('#apiid').val();           var apikey = $('#apikey').val();           var email = $('#email').val();             console.log("apiid  = ",apiid , " apikey = ",apikey , " email = ",email);      });    });  

Now I want to send apiid , apikey and email to my controller.

def api   //here I want apiid, apikey,email from js  end  

Splitting values in Hashmap

Posted: 21 Dec 2016 04:08 AM PST

I have a hashmap in the following format:

{"PPS_Id"=>["fe4d7c06-215a-48a7-966d-19ab58976548", "6e90208e-4ab2-4d44-bbaa-9a874bff095b"], "Amount"=>"[\"10000.000\", \"2374.000\"]"}  

When I write this data into an excel get the following output.

enter image description here I want to write the data into the Excel this way:

PPS_Id                                     Amount  fe4d7c06-215a-48a7-966d-19ab58976548       10000.000  6e90208e-4ab2-4d44-bbaa-9a874bff095b       2374.000  

How do I convert my current Hash to the below:

{PPS_Id"=>["fe4d7c06-215a-48a7-966d-19ab58976548","Amount"=>"10000.000"},{PPS_Id"=>["6e90208e-4ab2-4d44-bbaa-9a874bff095b","Amount"=>"2374.000"}  

Can you please assist.

Rails Activerecord nested has_many relation query

Posted: 21 Dec 2016 02:45 AM PST

I have the following models to support has_many through relations in rails active record

 class Comment < ApplicationRecord    # all the relations for the comment            belongs_to :user             belongs_to :commentable, :polymorphic => true    , belongs_to :community      has_many :comments, :as => :commentable  end         class Post < ApplicationRecord        # validations for the mush have properties in the database      validates :title, :content, presence: true        has_many :comments, :as => :commentable      has_many :attachments, :as => :attachable      belongs_to :author, :class_name => :user, :foreign_key => 'author'  end  

Now my comments inside a post can have multiple nested comments and again they in themselves can have multiple nested comments. Its a usecase of typical discussion forums threads.

Following is the query i am firing.

post = Post.eager_load(:followers, :user, :communities, :usertags => :user, :comments => [:comments,:usertags => :user]).select("*").find_by(:slug => slug)  

I am here able to find 1 level deep nested comments or by furthur workaround i may be able to go one level more deep.

Upto my knowledge this can be implemented using a SQL stored proc with if/else join statements which i want to avoid as i typically want to stick to activerecord ORM.

1) Is there any good/better approach to find all nested comments in the query where i don't need to build a query for nested comments because this approch will take down to level i define in query.

2) Now i am just 5 months into rails, but i also want a good/better approach to serialize the result activerecord object. As currently i have to loop through each comments to find the next nested comments and push it to some object/hash/array to build proper object which i can serialize for json. Sharing a code snippet here for the whole example

post = Post.eager_load(:followers, :user, :communities, :usertags => :user, :comments => [:comments,:usertags => :user]).select("*").find_by(:slug => slug)        # validation check to see if if the post is public        hide_content = false        if(current_user.blank? && post.is_private)        hide_content = true      end        comments_list = Array.new      post.comments.each do | comment|              comment_user = comment.user        comment_user_tags = comment.usertags          comment.usertags.each do | ut|          end          nested_comments_level_1 = Array.new          comment.comments.each do |c|            nested_comments_level_1_hash = {            :comment => c,            :user => c.user,            :usertags => c.usertags          }            nested_comments_level_1.push(nested_comments_level_1_hash)            end            comment_hash = {          :comment => comment,          :user => comment_user,          :usertags => comment_user_tags,          :comments_level_1 => nested_comments_level_1        }          comments_list.push(comment_hash)      end  

Now that nested_comment will be recursive, so i will convert this code to a reusable block for recursive, but is there a better approach to do this.

I have worked with ORM in cake, .NET which use to easily serialize all the associated objects on the main model object for response. Is a simillar thing possible with rails.

Thanks

Mongodb, mongoLab, Heroku (staging) and rails : Authentication fail

Posted: 21 Dec 2016 02:39 AM PST

I work on a project deployed on Heroku, with production and staging version. When I want to access to the mongo shell on staging writing this line : mongo <host/app> -u <username> -p <password> (with <> remplaced with my informations) I have this error :

2016-12-21T11:34:43.861+0100 E QUERY    [thread1] Error: Authentication failed. :  DB.prototype._authOrThrow@src/mongo/shell/db.js:1441:20  @(auth):6:1  @(auth):1:2    exception: login failed  

It work for production but not for staging. And when I want to do a mongorestore with all informations I have this error :

Failed: error connecting to db server: server returned error on SASL authentication step: Authentication failed  

Does someone could help me ?

sass-watch: command not found whenever I run sass-watch

Posted: 21 Dec 2016 02:44 AM PST

I have Ruby and sass installed already, but I'm getting a

sass-watch: command not found

Whenever I run

sass-watch .  

Any ideas?

rspec doesn't run first test case

Posted: 21 Dec 2016 02:11 AM PST

The block #update doesn't run. Why? How to change it to run all of them. #anything works fine.

describe UsersController, type: :controller do    login_admin      describe '#update' do      def user_update_params(roles:)        {          role_ids: roles.map(&:id),          name: 'new'        }      end        shared_examples_for 'update user' do        it 'change the user' do          expect do            put :update, id: user.id, user: user_params          end.to change { user.reload.name }        end      end    end      describe '#anything' do      it 'is ok' do        #runs ok      end    end  end  

Rails includes associations with left join conditions

Posted: 21 Dec 2016 02:02 AM PST

Consider these two associated models, Program and SpentFinance:

class Program < ApplicationRecord    has_many :spent_finances  end    class SpentFinance < ApplicationRecord  end  

Each spent finance has a time_period_type, such as 'year' or 'month'.

How can I retrieve all programs, and at the same time preload all associated spent_finances associated with a program that have a certain time_period_type?

Note:

  • The query must retrieve ALL programs, including programs that do not have any spent finances of the requested time period type.
  • Should provide a way to programmatically change the time_period_type in the query

These are the attempts I've made at cracking this problem.

First attempt

Program  .references(:spent_finances)  .includes(:spent_finances)  .merge(SpentFinance.where(time_period_type: time_period_type))  

This doesn't work, because it filters out programs that don't have spent finances with the specified time period type. (It adds the time_period_type condition to the WHERE clause and not the JOIN ON clause.)

Second attempt

class Program < ApplicationRecord    has_many :yearly_spent_finances,      -> { where(time_period_type: 'year') },      className: 'SpentFinance'  end    programs = Program.references(:yearly_spent_finances).includes(:yearly_spent_finances)    programs[0].yearly_spent_finances  

This works (the last line does not execute another query), and indeed it is the officially recommended solution. However, it doesn't allow me to programmatically specify the desired time_period_type. For example, if I want to do a similar query as above, but change the time_period_type to 'month', then I would have to add another association has_many :monthly_spent_finances.

Rails: How to create query "select * from <sub_query>" in Arels

Posted: 21 Dec 2016 01:51 AM PST

For example, I have this subquery:

def date_range        Arel::Nodes::NamedFunction.new('GENERATE_SERIES',             [start_date, end_date, Arel::Nodes::SqlLiteral.new('1 day')]).as('dates')     end  

This query will generate some sql such as:

GENERATE_SERIES(start_date, end_date, '1 day') AS dates  

Now I want to create another query that select from this subquery, for example:

 SELECT dates.date FROM <above_query>  

How can I do this in Arel query ? I have tried some but not work. for example:

dates = Arel::Table.new('dates')  dates.where(date_range).project(dates[:date])  

But it will generate a query such as:

SELECT dates.date from dates       where GENERATE_SERIES(start_date, end_date, '1 day') AS dates  

Please tell me how.

Thanks

Remove old ruby version [duplicate]

Posted: 21 Dec 2016 01:49 AM PST

This question already has an answer here:

I want to remove old Ruby versions from Centos 7. I tried this:

rvm list    rvm rubies       ruby-2.1.4 [ x86_64 ]  =* ruby-2.2.2 [ x86_64 ]     ruby-2.3.3 [ x86_64 ]    # => - current  # =* - current && default  #  * - default    [root@localhost ~]# gem uninstall ruby -v 2.1.4  

But again I see

rvm list        rvm rubies           ruby-2.1.4 [ x86_64 ]      =* ruby-2.2.2 [ x86_64 ]         ruby-2.3.3 [ x86_64 ]        # => - current      # =* - current && default      #  * - default        [root@localhost ~]# gem uninstall ruby -v 2.1.4  

Can you propose some solution?

2 comments:

  1. I was looking at some of your posts on this website and I conceive this web site is really instructive! Keep putting up..
    dg casino

    ReplyDelete
  2. This is such a great resource that you are providing and you give it away for free.
    Asia Gaming

    ReplyDelete