Wednesday, January 18, 2017

JSONResources gem: namespaced routes | Fixed issues

JSONResources gem: namespaced routes | Fixed issues


JSONResources gem: namespaced routes

Posted: 18 Jan 2017 07:43 AM PST

I'm playing with the JSONResources gem and it's having trouble getting named routes to show up in the links attribute when I hit an index action that paginates results.

In my config/routes file, I've got this:

scope :module => :api, defaults: { format: 'json' } do    constraints APIConstraints::APIVersion.new(1) do      scope :module => :v1 do        jsonapi_resources :guidelines      end    end  end  

The APIConstraints class mentioned above inspects the headers to see if the request specifies API version. If no version is specified, it'll set a default version (in this case, version 1).

When I inspect the routes, things look normal.

$ rake routes  Prefix Verb   URI Pattern               Controller#Action    guidelines GET    /guidelines(.:format)     api/v1/guidelines#index {:format=>"json"}  ...  

When I curl the endpoint to list various guidelines, it returns the payload I'd expect, but the links attribute completely ignores the named routes. I get something like this:

"links": {      "first": "http://localhost:3000/api/v1/guidelines?page%5Blimit%5D=30&page%5Boffset%5D=0",      "last": "http://localhost:3000/api/v1/guidelines?page%5Blimit%5D=30&page%5Boffset%5D=1250",      "next": "http://localhost:3000/api/v1/guidelines?page%5Blimit%5D=30&page%5Boffset%5D=30"  }  

When I read through the documentation, but I didn't see anything that addressed how to get the links attribute to respect the named routes.

Am I just misusing this gem's API or is there some way to accomplish this task?

Problems for request rspec with basic http auth using Devise

Posted: 18 Jan 2017 07:41 AM PST

Devise: 4.20  Rails: 5.0.1  Rspec: 3.5  

I had used this link https://github.com/plataformatec/devise/wiki/How-To:-Use-HTTP-Basic-Authentication, but I havproblems to test the http basic auth for my api using rspec for requests tests. Below is the example the error:

app/controllers/api/base_controller.rb

module Api    class BaseController < ApplicationController      before_action :authenticate_user!        protected        def authenticate_user!        authenticate_or_request_with_http_basic do |username, password|          resource = User.find_by_username(username)          if resource            sign_in :user, resource if resource.valid_password?(password)          else            request_http_basic_authentication          end        end      end    end  end  

app/controllers/api/v1/car_controller.rb

module Api    module V1      class CarController < Api::BaseController        respond_to :json          def index          @cars = Car.all          render :json => {:content => @cars}, :status => 200        end      end    end  end  

spec/requests/api/v1/server_controller_spec.rb

require 'rails_helper'    RSpec.describe "Servers API", :type => :request do    it 'sends a list of servers' do      admin = FactoryGirl.create(:admin)      @env = {}      @env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(admin.username, admin.password)      get "/api/cars", :params => {}, :headers => @env        # test for the 200 status-code      expect(response.status).to eq(200)      end  end  

When I run the spec, I have the below error:

# --- Caused by: ---       # NoMethodError:       #   undefined method `sign_in' for #<Api::V1::CarController:0x0000000609ef12>       # ./app/controllers/api/base_controller.rb:10 in block in authenticate_user!  

Anyone can help me? Thanks.

Rails ExtJS- How to include a new .png /.jpg image in the application

Posted: 18 Jan 2017 07:14 AM PST

I have a Rails and ExtJS application which has all images under

MyApplication/app/assets/graphics  

The styles are listed in the following file->

 MyApplication/app/assets/stylesheets/css/styles.less  

The following file seems to have a compiled version of all styles

MyApplication/app/assets/stylesheets/css/lt.css  

I added a new image test.png under graphics folder. How can I compile this into the styles? So far, when I refer to this image in my code, it doesn't show up since it is not in the lt.css file. Thanks!

Rails selenium visit command firefox

Posted: 18 Jan 2017 07:19 AM PST

I am trying to run selenium with capybara and minitest on ubuntu with firefox 50.1 but it won't visit any url. I just get firefox open but empty, but sometimes I get error 1:

testfile:

require "test_helper"     feature "dashboard" do       scenario "test" , :js=>true do      Capybara.current_driver = :selenium      visit("http://www.google.com/")        visit root_url      end  end    

gemfile:

 group :test do    gem 'selenium-webdriver', '~> 2.53', '>= 2.53.4'    gem 'minitest-reporters'     gem "minitest-rails-capybara"    

error1:

test_0001_test ERROR (65.56s) Selenium::WebDriver::Error::WebDriverError:
Selenium::WebDriver::Error::WebDriverError: unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055) test/features/instance_dashboard_test.rb:81:in `block (2 levels) in '

parsing json from google distance matrix

Posted: 18 Jan 2017 07:02 AM PST

In a rails application, the query to google's distance matrix returns proper data. The controller generates the result in an object

matrix.origins << origin  matrix.destinations << destination  matrix.data  @data = matrix.data  

which is an array of hashes. the instance variable @data

returns [[#<GoogleDistanceMatrix::Route origin: #<GoogleDistanceMatrix::Place lat: 61.1173, lng: 13.8875>, destination: #<GoogleDistanceMatrix::Place lat: 61.3405325, lng: 13.7243266>, status: "ok", distance_text: "56.9 km", distance_in_meters: 56948, duration_text: "1 hour 6 mins", duration_in_seconds: 3944>]]

However the <%= data["distance_text"].to_s %> statement generates a no implicit conversion of String into Integer when I am not interested in the integer. Thus I suspect it is calling the index, when I expected the each command to handle it. How can this be done properly?

How to install jquery-ui/datepicker in rails 4 application?

Posted: 18 Jan 2017 07:20 AM PST

I installed ActiveAdmin on my rails application, and now get the following error message when loading my view. It says:

"couldn't find file 'jquery-ui/datepicker' with type 'application/javascript'"  

Extracted source (around line #6): <%= stylesheet_link_tag'application', media: 'all', 'data-turbolinks-track' => true %>

I tried the answer on Rails 4 - how to install "jquery-ui"?

but it didn't work. Can anyone help?

Reload a specific tab after call ajax

Posted: 18 Jan 2017 06:14 AM PST

I would like reloading my page after a call Ajax. It works with location.reload() but i'm redirect to the first tab. How can i just reload my tab ?

HTML

<div class="tabs">    <a class="tab" data-target="#profile">      <h3 class="tab-title active" data-target="#profile">Mes informations</h3>    </a>    <a class="tab" data-target="#prayers">      <h3 class="tab-title" data-target="#prayers">Mes prières</h3>    </a>    <a class="tab" data-target="#pains" id="tab-pains">     <% if (@notification && @notification.count > 0) %>       <h3 class="tab-title" data-target="#pains">Mes demandes <span id="tab-notification">(<%= @notification.count %>)</span></h3>     <% else %>       <h3 class="tab-title" data-target="#pains">Mes demandes </h3>     <% end %>   </a>  </div>  

JQuery

$(document).ready(function() {   $(".user-show-delete").on("click", function(e){    var id = $(this).data("id");    var pain_id = $(this).data("id-pain");    console.log(id)    console.log(pain_id)    var current_index = $("#tabs").tabs("option","active");    swal ({      title: 'Effacer',      text: 'Voulez-vous supprimer cette prière ?',      type: 'question',      showCancelButton: true,      confirmButtonColor: '#B56969',      cancelButtonColor: '#B4D8C0',      confirmButtonText: 'Oui',      cancelButtonText: 'Non'    }).then(function() {      $.ajax({        type: 'DELETE',        url: '/pains/' + pain_id + '/prayers/' + id,        success: function() {          var tabId = $("#tab-title").tabs("option", "active");          $("#tab-title").tabs("load", tabId);        }      });    });   });  });  

Thanks for your answers

Rails : find all associated entries habtm

Posted: 18 Jan 2017 06:39 AM PST

I have a model Documentand a model KeyWord.

The table keywords has a lot more entries than keywords are associated to documents.

I need to select only those keywords that are actually attributed to Document.

I've tried:

Document.keywords.map { |e| e.keywrd }  

and this :

Document.keywords.select(:keywrd)  

That returns this error :

NoMethodError: undefined method `keywords' for #<Class:0x007fcd100d2b38>  

Printing value in rails

Posted: 18 Jan 2017 06:54 AM PST

If I have variable that looks like this

[{"value"=>"4"}]  

When I do in a view:

<%= @res.inspect %>  

How do I print it?

I just want to show value of value in my view, what would the code look like?

Rails REST doesn't show/load the right page - Ruby on Rails

Posted: 18 Jan 2017 05:44 AM PST

Basically I created a controller, model and view for subjects. Basically I have 6 actions inside my controller and set up a REST inside my routes file to route the right file.

When I entered, http://localhost:3000/subjects/index it shows me the view for show.html.erb instead of the index.html.erb

Here's what my subject controller looks like:

class SubjectsController < ApplicationController    def index      @subjects = Subject.sorted    end  

And here's the content of my index.html.erb file.

<% @page_title = "All Subjects" %>    <div class="subjects index">  <h2>Subjects</h2>    <%= link_to("Add New Subject", new_subject_path, :class => "action_new") %>    <table class="listing" summary="Subject list" border="1">  <tr class="header">  <th>#</th>  <th>Subject</th>  <th>Visible</th>  <th>Pages</th>  <th>Actions</th>  </tr>    <% @subjects.each do |subject| %>  <tr>    <td><%= subject.position %> </td>    <td><%= subject.name %> </td>    <td class="center"><%= status_tag(subject.visible) %></td>    <td class="center"><%= subject.pages.size %> </td>    <td class="actions">      <%= link_to("View Pages", pages_path(:subject_id => subject.id), :class => 'action show') %>      <%= link_to("Show", subject_path(subject), :class => 'action show') %>      <%= link_to("Edit", edit_subject_path(subject), :class => 'action edit') %>      <%= link_to("Delete", delete_subject_path(subject), :class => 'action delete') %>    <td>    </tr>    <% end %>    <table>  </div>  

Also here's what I set up on my routes:

  resources :subjects do      member do        get :delete      end    end  

Any idea what am I missing?

Rails has_many :through, cocoon

Posted: 18 Jan 2017 05:23 AM PST

Player.rb

class Player < ApplicationRecord  belongs_to :user  has_many :player_games, dependent: :destroy, inverse_of: :player  has_many :games, :through => :player_games    validates :firstname, presence: true, length: { minimum: 3, maximum: 88 }  validates :lastname, presence: true, length: { minimum: 3, maximum: 88 }  validates :user_id, presence: true    accepts_nested_attributes_for :player_games, reject_if: :reject_posts, allow_destroy: true    def reject_posts(attributes)      attributes['game_id'].to_i == 0      attributes['score'].blank?      attributes['time'].blank?  end    def initialized_player_games # this is the key method      [].tap do |o|          Game.all.each do |game|              if g = player_games.find { |g| g.game_id == game.id }                  o << g.tap { |g| g.enable ||= true }              else                  o << PlayerGame.new(game: game)              end          end      end  end  end  

players_controller.rb

class PlayersController < ApplicationController  before_action :set_player, only: [:edit, :update, :show, :destroy]  before_action :require_user, except: [:index, :show]  before_action :require_same_user, only: [:edit, :update, :destroy]    before_filter :process_player_games_attrs, only: [:create, :update]    def process_player_games_attrs    params[:player][:player_games_attributes].values.each do |game_attr|      game_attr[:_destroy] = true if game_attr[:enable] != '1'    end  end  

.......

private    # Use callbacks to share common setup or constraints between actions.    def set_player      @player = Player.find(params[:id])    end      # Never trust parameters from the scary internet, only allow the white list through.    def player_params      params.require(:player).permit(:id, :firstname, :lastname, player_games_attributes: [:id, :game_id, :score, :time, :enable, :_destroy] )    end      def require_same_user      if current_user != @player.user and !current_user.admin?        flash[:danger] = "You can edit or delete only your own player"        redirect_to root_path      end     end    end  

_form of 'PLAYER'

<%= form_for(@player, :html => {class: "az-form", role: "form"}) do |player_form| %>      <%= player_form.label :firstname, class: "az-form__label" %> <br/>    <%= player_form.text_field :firstname, class: "az-form__input", placeholder: "Firstname of player", autofocus: true %>      <%= player_form.label :lastname, class: "az-form__label" %> </br>    <%= player_form.text_field :lastname, class: "az-form__input", placeholder: "Lastname of player" %>      <%= player_form.fields_for :player_games, @player.initialized_player_games do |builder| %>        <% @game = builder.object.game %>        <%= render 'result_fields', f: builder %>        <div class="links">        <%= link_to_add_association 'add result', player_form, :player_games, :partial => 'players/result_fields' %>      </div>        <hr>      <% end %>      <div class="text-center">      <%= button_tag(type: "submit", class: "az-form__submit") do %>          <%= player_form.object.new_record? ? "Create player" : "Update player" %>      <% end %>    </div>    <% end %>  

_result_fields.html.erb

<div class="nested-fields">    <%= f.hidden_field :game_id, :value => @game.id%>    <div class="row">    <div class="col-md-12">      <label class="az-form__label az-form__label--unable js-az-form__checkbox" data-check="<%= @game.id %>">        <%= f.check_box :enable %>        <%= @game.title %>       </label>    </div>   </div>    <div class="row">    <div class="col-md-6">      <%= f.label :score,                      class: "az-form__label", :data => {:check => @game.id } %> </br>       <%= f.number_field :score, step: :any, :data => {:check => @game.id },                             class: "az-form__input az-form__input--disabled",                             placeholder: "Score for '#{@game.title}'", disabled: true %>        </div>        <div class="col-md-6">       <%= f.label :time,                      class: "az-form__label", :data => {:check => @game.id } %> </br>    <%= f.number_field :time, step: :any, :data => {:check => @game.id },                             class: "az-form__input az-form__input--disabled",                             placeholder: "Time for '#{@game.title}'", disabled: true %>     </div>   </div>     <div class="row">    <div class="col-md-12">     <%= link_to_remove_association "remove result", f %>      </div>    </div>    </div>  

Question:

When edit 'player' have access to only one result per game, can not change others, conflict with 'initialized_player_games' method, but if i remove this method from form work well, but cannot create another game if dont create in new action, how can i change this method properly?

How to change security group for existing amazon EC2 ubuntu

Posted: 18 Jan 2017 05:16 AM PST

I tried changing the instance security group by right click and then "change security groups", but it's grayed out.

Update:-
I have a rails application and I want give the response for particular Ip(ex: 12.123.12.456) requets, if the request from that IP(ex: 12.123.12.456) then give the response otherwise no response..
so i am trying to change security group in aws..

what to do?

How to list all open source components used in a rails application?

Posted: 18 Jan 2017 04:33 AM PST

I need to create a list of all Open Source Components being used in my Rails application.

Is there a quick way to do this or I have to go through whole application and create the list?

Ruby on rails errors on command “rails server“ [duplicate]

Posted: 18 Jan 2017 05:17 AM PST

This question already has an answer here:

Here is my stack trace:

Rails server stack trace

I'm running Ubuntu 16.10 x64.

Rails + Passenger + Nginx + Dokku 504 after 1 minute of activity

Posted: 18 Jan 2017 04:11 AM PST

Got a rails app currently running and stable on heroku server (512mb ram)

I took the app as is and put it on dokku (with intercity) on a ubuntu server 14gb ram 2 cpu(azure).

The app spins and works very fast, everything looks fine.

After 1 min of inactivity I refresh the browser and get a

504 Gateway Time-out

I try search for errors or any memory issues but the only thing looks wrong is the

17/01/18 11:24:18 [error] 61198#61198: *2071 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 79.184.17.155, server: cltvf.site, request: "GET /campaigns/5874e4d14bc3600a4a19566/details HTTP/1.1", upstream: "http://172.11.0.3:5000/campaigns/587f4e4d4bc3600a4a19566/details", host: "cltvf.site", referrer: "http://cltv.site/an/u_request_approve"

I got from the

nginx:error-logs

command

the 172.11.0.3 is an internal ip, if helps.

when trying to check if there is a memory issue I saw

CONTAINER           CPU %               MEM USAGE / LIMIT       MEM %               NET I/O               BLOCK I/O           PIDS  

ac513d4dd4ea 0.00% 199.8 MiB / 13.69 GiB 1.43% 296.7 kB / 156.5 kB 0 B / 0 B 13 a296ec88b1ef 0.01% 254.2 MiB / 13.69 GiB 1.81% 282.5 kB / 111.4 kB 0 B / 614.4 kB 52 beb69ddc4351 0.13% 254.3 MiB / 13.69 GiB 1.81% 286.9 kB / 112.5 kB 0 B / 614.4 kB 51 43665198a31b 0.00% 231.8 MiB / 13.69 GiB 1.65% 19.33 MB / 21.8 MB 0 B / 0 B 12 7d374f36b240 0.00% 231.6 MiB / 13.69 GiB 1.65% 19.34 MB / 21.81 MB 0 B / 0 B 13 04e98f7914b0 0.01% 343.9 MiB / 13.69 GiB 2.45% 14.37 MB / 9.091 MB 0 B / 614.4 kB 51 1255e7837b19 0.20% 231.5 MiB / 13.69 GiB 1.65% 19.34 MB / 21.78 MB 0 B / 0 B 12 378302bbdb84 0.00% 55.11 MiB / 13.69 GiB 0.39% 64.81 kB / 4.737 kB 0 B / 225.3 kB 40 5b8eb7a5423e 0.01% 52.47 MiB / 13.69 GiB 0.37% 71.75 kB / 8.718 kB 0 B / 225.3 kB 40

You can see nothing serious

same for disk usage

dev/sda1 28G 7403M 21G 25.5 [##########............................] /
/dev/sdb1 27G 44M 26G 0.2 [......................................] /mnt
/dev/sda1 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs
none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/4631d50385f25bf480fc18f5f2c7d93052b0f2ffecd6d04a14076513344b7338 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/4f8488bdd0a683fda71a6789165d44626215ef4ce00f7d6c70c7ff64d7d89c14 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/553fb1ea82841dd534450e9929513b90d17e4be73e271b861716d8f240ef8d17 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/6909bba1bea70a3781f55bea3d059a014ddae8638021bf4f9a82edffab63cc94 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/7200a36e8f3ca4e9358f83aad1ac5de562068f6458045f291812b8ab9e769abf none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/bd289b0106072a2946e40a60bacb2b1024d1075996aff5bb3388290617ad85b2 none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/bd4d4632764af3a8e61b6da8d5f137addc2044615a5a36e72f675a180e6f7c7c none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/e050fcacaeb0d9cb759bc72e768b2ceabd2eb95350f7c9ba6f20933c4696d1ef none 28G 7403M 21G 25.5 [##########............................] /var/lib/docker/aufs/mnt/ffd758a6189aab5eac81950df15779f84f7c93a2a81b1707b082cee2202ece4d

I'm posting this question after hours of googling.

thanks

Rails Eager loading has_many associations for an existing object

Posted: 18 Jan 2017 05:49 AM PST

I am fairly new to rails & I am having this performance issue that I would appreciate any help with.

I have a User model & each user has_many UserScores associated. I am preparing a dashboard showing different user stats including counts of user_scores based on certain conditions. Here is a snippet of the code:

def dashboard  @users = Array.new  users = User.order('created_at ASC')  users.each do |u|      user = {}      user[:id] = u.id      user[:name] = u.nickname      user[:email] = u.email      user[:matches] = u.user_scores.count      user[:jokers_used] = u.user_scores.where(:joker => true).length      user[:jokers] = u.joker      user[:bonus] = u.user_scores.where(:bonus => 1).length    user[:joined] = u.created_at.strftime("%y/%m/%d")      if user[:matches] > 0          user[:last_activity] = u.user_scores.order('updated_at DESC').first.updated_at.strftime("%y/%m/%d")      else          user[:last_activity] = u.updated_at.strftime("%y/%m/%d")      end      @users << user  end  @user_count = @users.count  

end

The issue I am seeing is repeated UserScore db queries for each user to get the different counts.

Is there a way to avoid those multiple queries??

N.B. I'm not sure if my approach for preparing data for the view is the optimal way, so any advice or tips regarding that will be greatly appreciated as well.

Thanks

Random ActionController::InvalidAuthenticityToken

Posted: 18 Jan 2017 07:18 AM PST

I get random ActionController::InvalidAuthenticityToken errors on my production server. There are no AJAX requests, all forms are created with Rails helpers (so they do include hidden field with authenticity_token).

The problem appears randomly on random forms.

In my ApplicationController I have before_action :expires_now. Could that be a problem? I added this because my users often click 'back' in their browsers and I didn't want them having cached results.

My session_store.rb initializer looks like this:

Rails.application.config.session_store :cookie_store, key: '_myapp_session'  

If that makes any difference I use Devise with timeoutable module and its config.timeout_in set to 1.hour.

I'm using Rails 5.0.1.

application_controller.rb:

class ApplicationController < ActionController::Base    include Pundit    rescue_from Pundit::NotAuthorizedError, with: :not_authorized    protect_from_forgery with: :exception    add_flash_types :success, :warning, :danger, :info    before_action :authenticate_user!    before_action :set_current_user    before_action :set_cache_headers      def after_sign_out_path_for(_user)      tasks_path    end      def not_authorized      flash[:warning] = 'You are not authorized to execute this action.'      redirect_to tasks_path    end      private      def set_current_user      User.current = current_user    end      def set_cache_headers      response.headers['Cache-Control'] = 'no-cache, no-store'      response.headers['Pragma'] = 'no-cache'      response.headers['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT'    end  end  

List sub controllers in Rails

Posted: 18 Jan 2017 03:38 AM PST

In my Rails app I have an AdminController in app/controllers/admin:

module Admin    class AdminController < ApplicationController      end  end  

And then inside the admin folder I have various other controllers which all inherit from the AdminController, e.g.

module Admin    class PermissionsController < AdminController      end  end  

I'm trying to list all the controllers and actions under AdminController with:

def list    @controllers = AdminController.descendants  end  

But all I get is: Admin::PermissionsController

I've also tried AdminController.subclasses but get the same.

I don't want to do @controllers = Dir.new("#{Rails.root}/app/controllers/admin").entries because I also want to access the action_methods.

Why isn't descendants or subclasses working?

In my view I want to do:

<% @controllers.each do |controller| %>      <h2><%= controller %></h2>      <ul>        <% controller.action_methods.each do |action| %>            <li><%= action %></li>        <% end %>      </ul>  <% end %>  

Which does list all the actions but only for the current controller and it also lists action methods from the parent controllers. I only want to list the ones for each controller.

Video tag not working with rails on Safari

Posted: 18 Jan 2017 03:28 AM PST

I have a video tag that works in both Chrome and Firefox but not with Safari. Here is my tag

On html:

<%= video_tag("working.mp4", class:"video", autoplay: :autoplay, loop: :loop, mute: :mute, poster: "working.jpeg") %>  

On css:

.video {  position: absolute;  top: 50%; left: 50%;  width:100%;  height: 870px;  z-index:1;  object-fit: cover;  transform: translate(-50%, -50%);  display:block !important;  

}

The video currently lives in "assets/video/working.mp4"

How do I use spree commerce extension spree_wishlist api?

Posted: 18 Jan 2017 03:03 AM PST

I am using a spree_wishlist extension to spree eCommerce application, I want to access wishlist API for mobile, is there any possibility?

Finding out unread mails which do not have certain keywords included in the subject in my mailbox using Mail gem

Posted: 18 Jan 2017 04:01 AM PST

I am able to read the unread emails with the word "development" from my mailbox using:

Mail.find(keys: ['UNSEEN','SUBJECT',"development"],:count => 100,:what =>:all).  

I now want to retrieve the unread mails from my mailbox with out the word "development" in subject line.

I read RFC2060, section 6.4.4, and tried UNKEYWORD AND NOT methods, but it didn't help. Can anybody suggest me an appropriate answer for the same?

ruby on rails will_paginate change default link

Posted: 18 Jan 2017 05:11 AM PST

In the routes.rb I set lists#index as the root:

root to: "lists#index"

I would like will_paginate to create page hrefs pointing to /?page=# instead of /lists?page=#. To create the paginate links I have the following line in the "lists#index" file:

<%= will_paginate @lists %>

List sessions for current user only in Rails

Posted: 18 Jan 2017 06:42 AM PST

I'm using the activerecord-session_store gem to store sessions in the database.

I list sessions with this method in my SessionsController:

def index    @sessions = Session.all  end  

However this lists ALL sessions in the app and not just ones for the currently logged in user. The database table for sessions has the following columns: id, session_id, data, created_at, updated_at so there is no user_id column to filter on.

I can access the user_id in the session data with Marshal.load(Base64.decode64(session.data))['user_id']

How can I use this data to filter the list? So far all I can think of is to do a conditional in the View that compares it against the current_user.id

e.g.

<% @sessions.each do |session| %>    <% if Marshal.load(Base64.decode64(session.data))['user_id'] == current_user.id %>      <!-- LIST SESSION -->    <% end %>  <% end %>  

how to set Mandrill with DKIM and SPF in order to receive the activation link via mail

Posted: 18 Jan 2017 02:32 AM PST

I am working on a new app (Ruby On Rails) and I have been stocked on Mandrill. The settings are fine because when I try to register a new user I can see in the terminal the actiovation link and I can go through my registration but I don't receive any mails because I have no idea how to set this:

I tried to follow all the guides but I didn't get them. Where should I CHANGE these settings? Thanks for your help

Respect negative conditions for advanced collection associations

Posted: 18 Jan 2017 02:32 AM PST

I was trying to use this functionality introduced in #645 with conditional 2nd degree has_many ... through relationships with little success.

In my case:

  • a Course has_many :user_assigned_content_skills, -> { where(source: 'user') }, class_name: "ContentSkill"
  • and a ContentSkill belongs_to :skill and belongs_to :course

Then Course.ransack({user_assigned_content_skills_skill_name_not_cont: 'ruby'}).result.to_sql returns the following:

"SELECT courses.* FROM courses LEFT OUTER JOIN content_skills ON content_skills.course_id = courses.id AND content_skills.source = 'user' LEFT OUTER JOIN skills ON skills.id = content_skills.skill_id WHERE (skills.name NOT ILIKE '%ruby%')"

This means false positives again if a course has multiple content_skills. Any ideas how to retrieve all courses not being associated with a given skill name?

Many thanks for any insights!

Sending message from autobahn Android

Posted: 18 Jan 2017 02:20 AM PST

I've got a Rails websocket/server set up and want to send messages from my phone to the server. The implementation of Autobahn is the following (template):

private final WebSocketConnection mConnection = new WebSocketConnection();    private void start() {       final String wsuri = "ws://localhost:9000";       try {        mConnection.connect(wsuri, new WebSocketHandler() {             @Override           public void onOpen() {              Log.d(TAG, "Status: Connected to " + wsuri);              mConnection.sendTextMessage("Hello, world!");           }             @Override           public void onTextMessage(String payload) {              Log.d(TAG, "Got echo: " + payload);           }             @Override           public void onClose(int code, String reason) {              Log.d(TAG, "Connection lost.");           }        });     } catch (WebSocketException e) {          Log.d(TAG, e.toString());     }  }  

That is working fine for receiving, but how do I send something back?

Rails 4 - controller not being called

Posted: 18 Jan 2017 04:39 AM PST

I can hit the importers#import_vendor_ledger action but I can't seem to hit the importers#import_chart_of_accounts action via the redirect_based_on(arg) method inuploaders#upload_file. Please help!

NOTE: I left out some code that I didn't think was necessary to see

My code:

routes.rb

resources :uploaders do     collection { post :upload_file }  end    resources :importers do     collection { post :import_vendor_ledger, :import_chart_of_accounts }  end  

index.html.haml

#chart_of_accounts    = form_tag upload_file_uploaders_path, multipart: true do      = hidden_field_tag :account, "chart_of_accounts"      = file_field_tag :file      = submit_tag 'Upload Chart of Accounts'    #vendor_ledger    = form_tag upload_file_uploaders_path, multipart: true do      = hidden_field_tag :account, "vendor_ledger"      = file_field_tag :file      = submit_tag 'Upload'  

uploaders_controller.rb

class UploadersController < ApplicationController    include Excel      def upload_file      uploaded_io = params[:file]      if uploaded_io.path.downcase.end_with?(xlsx_extension)        save_to_storage(uploaded_io)        flash[:success] = 'File uploaded successfully!'        redirect_based_on_(params) # this is where it should call the action      else        flash[:warning] = 'ERROR: The file you upload MUST be an ".xlsx" excel file!'        redirect_to root_url      end    end      private      def redirect_based_on_(_params)      case _params[:account]      when "vender_ledger"        redirect_to import_vendor_ledger_importers_path and return      when "chart_of_accounts"        redirect_to import_chart_of_accounts_importers_path and return      end    end  end  

importers_controller.rb

class ImportersController < ApplicationController    include Excel      def index    end      def show    end      def import_vendor_ledger  # I can hit this action      puts "hits vendor ledger import"    end      def import_chart_of_accounts  # but I can't hit this action      puts "hits chart of accounts import"    end  

EDIT #1: even if I explicitly call redirect_to import_chart_of_accounts_importers_path in uploaders#upload_file it still doesn't hit the importers#import_chart_of_accounts action

EDIT #2: after inspecting more, it seems that importers#import_chart_of_accounts action IS being hit, but none of the functions in the action is being called

can't dynamically add activeadmin gem to autoload_paths

Posted: 18 Jan 2017 06:06 AM PST

I am using heroku for my main app, but now i have separated it to main_app and admin_app (memory issues).

So i have 2 apps running on the same git repo with no problems.

main_app uses subdomain admin. to resolve admin_app

now i want to save some memory without loading active admin.

i use a group in gemfile

group :admin_app do    gem 'activeadmin', git: 'https://github.com/activeadmin/activeadmin'  end  

and in application.rb when admin_app loaded

 Bundler.require(*Rails.groups,:admin_app)   

Now, i have the admin folder which is located on app/admin gets auto loaded so i have to ignore it or else i get an exception (no active_admin gem on main_app)

i solved it by a simple if statement

if Rails.application.secrets.admin_app    ActiveAdmin.register ForumTopic ....    end  

i am looking for a better fix for this problem .

i tried moving admin folder to lib or outside the app folder and then add it to

config.autoload_paths << Rails.root.join('admin')  

but i just don't see it get loaded when using

ActiveSupport::Dependencies.autoload_paths  

i whould like to hear your ideas, thank's

Base collection_select on selected value from other

Posted: 18 Jan 2017 02:05 AM PST

I googled for a while and tried different things, but none seem to be working or they all seem to be focused on using 2 tables. The question i have is: How do i populate 1 dropdown based on the selected value of another dropdown.

I have a table: Measurements, where i first want to select a measurement_type and then in the second table one of the measurements belonging to that type.

Convert DXF file to JSON Geometry 4

Posted: 18 Jan 2017 01:24 AM PST

I'm trying to use Threejs.org . I need to upload my 3D DXF file and show it on my page using Threejs. But I have no idea how to convert it. Dxf-parser is working for 2D images only. Could you please help me find the solution how to convert my .dxf file to json geometry 4 which is used by three.js or any other solution.

My project is in Ruby Rails. Maybe this could help. Sorry for my english. I'll appreciate any help.

No comments:

Post a Comment