Wednesday, September 28, 2016

nested form, attribute from associated model | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

nested form, attribute from associated model | Fixed issues


nested form, attribute from associated model

Posted: 28 Sep 2016 07:45 AM PDT

I have an Agenda model that has_many timeslots. A Timeslot belongs_to an Agenda.

My Agenda form uses nested attributes to collect and persist the timeslot information. The Agenda model has a begin_date field.

The Timeslot model has a virtual attribute called time_range to set the Timeslot:tstart and Timeslot:tend attributes. I use this approach to have one form field for both start and end times.

class Timeslot < ActiveRecord::Base    belongs_to :agenda      validates_presence_of :tstart, :tend      def time_range=(val)      self.tstart, self.tend = val.split(' - ').map { |v| Time.zone.parse(v) }    end      def time_range      [tstart, tend].map { |t| t.strftime "%H:%M" }.join(' - ') if tstart && tend    end    end  

In order to set the appropriate date for tstart and tend, I need the value of the begin_at attribute from the Agenda model in my time_range method.

Any ideas on how?

Active Record Rails Inheritance - Auto Type casting based on type

Posted: 28 Sep 2016 07:40 AM PDT

My scenario


-> User has many machines

-> Machines can have 5 types

-> each machine type has its own processing mechanism.

-> I want to use type column to see which class this row belongs to. (Rails inheritance approach) as explained in this link Link.


My Question


-> access a machine from database e.g machine = Machine.first

-> then call machine.process (this process method should be called based upon the type of this machine). (I am expecting some type casting stuff here.)

Note: Each machine type has its process implementation which is different from other and it implemented in its own class.

I want to know best approach to implement this. Any help is appreciated.

Getting an error while creating customer profile in authorize.net

Posted: 28 Sep 2016 07:36 AM PDT

I am creating the Customer Profile in which i want to store shipping address of customer. For this the code is -

  customer_profile_request = CreateCustomerProfileRequest.new    customer_profile_request.profile = CustomerProfileType.new(Digest::MD5.hexdigest('asda')[0,10], user.full_name, user.email,nil,nil)    full_address = user.customer_addresses.primary_address.try(:truncate_full_address) || 'Address'    customer_profile_request.profile.shipToList = CustomerAddressType.new(user.first_name,       user.last_name, nil, full_address,       user.customer_addresses.primary_address.city,       user.customer_addresses.primary_address.state, user.customer_detail.zipcode, nil, nil, nil)    customer_profile_response = initialize_transaction.create_customer_profile(customer_profile_request)  

And i am getting an error -

"The element 'shipToList' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' cannot contain text. List of possible elements expected: 'firstName, lastName, company, address, city, state, zip, country, phoneNumber, faxNumber, email' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."

Am i missing something?

Ruby on Rails solr textbox filter/facet

Posted: 28 Sep 2016 07:14 AM PDT

So im trying to implement a TextBox in the facet area , that will get what the user has typed and make it a facet value and filter the results with it!

Any ideas ?

Here's how im using facets atm

View:

<h6>Μάρκα</h6>      <ul class="facetlist">          <% for row in @search.facet(:make).rows %>          <li>              <% if params[:make].blank? %>              <%= link_to(row.value, params.merge(:page  => 1,:make => row.value).permit!) %> <small class="rowcount"><%= row.count %></small>              <% else %>              <strong><%= row.value %></strong> (<%= link_to "remove", :make => nil %>)              <% end %>          </li>          <% end %>      </ul>  

Controller

def search      @search = Sunspot.search(Classified ) do           paginate(:page => params[:page] || 1, :per_page => 10)          order_by(:created_at , :desc)          fulltext params[:search]          with(:created_at)            active_make = with(:make , params[:make]) if params[:make].present?                   facet(:make)                  end        @classifieds = @search.results    end  

So now :make fields are rendered as facets and i can filter my results by clicking on them (which i suppose passes a parameter) , but how can i do this with a textbox? i tried various ways and failed

Typeahead and tagging

Posted: 28 Sep 2016 07:31 AM PDT

I have a route in my rails app that return a json array with all the tags that already been used. I want to use this array to help user write tags using Bootstrap Tags Input and Typeahead.

$.getJSON(      //path to json,      function(data) {          // data is an array like: ["tag1", "tag2", "tag3"]          var tagnames = new Bloodhound({            datumTokenizer: Bloodhound.tokenizers.whitespace,            queryTokenizer: Bloodhound.tokenizers.whitespace,            locals: data          });            $('#input_target').tagsinput({            typeaheadjs: {              name: 'tagnames',              source: tagnames            }          });      }  );  

I have tried this way and the way described on Bootstrap Tags Input but none of them works. What am I doing wrong?

How can I avoid deadlocks on my database when using ActiveJob in Rails?

Posted: 28 Sep 2016 07:06 AM PDT

I haven't had a lot of experience with deadlocking issues in the past, but the more I try to work with ActiveJob and concurrently processing those jobs, I'm running into this problem. An example of one Job that is creating it is shown below. The way it operates is I start ImportGameParticipationsJob and it queues up a bunch of CreateOrUpdateGameParticipationJobs.

When attempting to prevent my SQL Server from alerting me to a ton of deadlock errors, where is the cause likely happening below? Can I get a deadlock from simply selecting records to populate an object? Or can it really only happen when I'm attempting to save/update the record within my process_records method below when saving?

ImportGameParticipationsJob

class ImportGameParticipationsJob < ActiveJob::Base    queue_as :default      def perform(*args)      import_participations(args.first.presence)    end      def import_participations(*args)      games = Game.where(season: 2016)      games.each do |extract_record|        CreateOrUpdateGameParticipationJob.perform_later(extract_record.game_key)      end    end     end  

CreateOrUpdateGameParticipationJob

class CreateOrUpdateGameParticipationJob < ActiveJob::Base    queue_as :import_queue       def perform(*args)       if args.first.present?         game_key = args.first           # get all particpations for a given game         game_participations = GameRoster.where(game_key: game_key)         process_records(game_participations)       end     end       def process_records(participations)       # Loop through participations and build record for saving...       participations.each do |participation|         if participation.try(:player_id)           record = create_or_find(participation)           record = update_record(record, participation)         end           begin           if record.valid?             record.save           else             end         rescue Exception => e           end       end     end       def create_or_find(participation)       participation_record = GameParticipation.where(         game_id: participation.game.try(:id),         player_id: participation.player.try(:id))         .first_or_initialize do |record|           record.game = Game.find_by(game_key: participation.game_key)           record.player   = Player.find_by(id: participation.player_id)           record.club     = Club.find_by(club_id: participation.club_id)           record.status   = parse_status(participation.player_status)       end       return participation_record     end       def update_record(record, record)       old_status = record.status       new_status = parse_status(record.player_status)       if old_status != new_status         record.new_status = record.player_status         record.comment    = "status was updated via participations import job"       end       return record     end    end  

Why including Rescuable module doesn't work?

Posted: 28 Sep 2016 07:42 AM PDT

class MyKlass      include ActiveSupport::Rescuable      rescue_from Exception do      return "rescued"    end      #other stuff  end  

MyKlass is pure ruby object, but defined inside Rails application.

If I try to invoke MyKlass instance in rails console and then apply to it method which certainly should raise Exception, nothing happens other than error expected to be rescued.

Expecting messages that do not change application state in RSpec

Posted: 28 Sep 2016 06:54 AM PDT

In testing literature, you hear not to assert on outgoing messages unless they change the state of something else. In other words, query messages that don't affect state are stubbed with allow().with().and_return().

The problem I have with this method is that when all of these allows happen in the before block, when a method's parameters change, every test will fail. This is because the allow().with() block will not be triggered.

Consider this example:

describe('#some_endpoint') do    let(:another_class) { instance_double(AnotherClass) }    let(:presenter) { instance_double(Presenter) }      before do      allow(another_class).to receive(:presenter).with(some_args).and_return(presenter)    end      it 'assigns the correct presenter' do      get :some_endpoint      expect(assigns(:presenter)).to eq(presenter)    end      it 'responds with ok status' do      get :some_endpoint      expect(subject).to have_http_status(:ok)    end      it 'does something else' do      .....    end  end  

This example follows the testing literature and does not assert on another_class.presenter because that is a query message. If, however, the expected arguments to the presenter, some_args changes in the code, all tests will fail. This is much easier to debug if only the assigns the correct presenter test fails, which is the actual failure in the case of an argument change; because the presenter that is returned is not the correct presenter. The following tests would accomplish that goal:

describe('#some_endpoint') do    let(:another_class) { instance_double(AnotherClass) }    let(:presenter) { instance_double(Presenter) }      before do      allow(another_class).to receive(:presenter).and_return(presenter)    end      it 'assigns the correct presenter' do      get :some_endpoint      expect(another_class).to have_received(presenter).with(some_args)      expect(assigns(:presenter)).to eq(presenter)    end      it 'responds with ok status' do      get :some_endpoint      expect(subject).to have_http_status(:ok)    end      it 'does something else' do      .....    end  end  

What are the disadvantages of testing this way? I only see advantages. If this is the case, why is it that the testing community suggests not testing query messages?

bootstrap search rails look and feel

Posted: 28 Sep 2016 06:57 AM PDT

I've got a nice bootstrap navigation menu with a search box in it.

I've got it in a partial file...

      <form class="navbar-form navbar-left">      <div class="form-group">        <input type="text" class="form-control" placeholder="Search">      </div>      <button type="submit" class="btn btn-default">Submit</button>    </form>  

I like the layout of this search box. Unfortunately, I can't figure out how to get my rails search box to look the same...

<%= search_form_for @search do |f| %>  <div class="field">    <%= f.label :title_or_template_cont, "Search" %>    <%= f.text_field :title_or_template_cont %>      </div>   <div class="actions">  <%= f.submit "Search" %>  

What changes do I need to make in my rails form to look like the bootstrap search box?

I tried a few classes within the rails search box, but wasn't close to the way it looked.

Any suggestions?

How do I test Devise confirm with Minitest?

Posted: 28 Sep 2016 06:35 AM PDT

How can I construct a get to test devise confirmation in my Rails 5 application with minitest?

I'm trying to test Devise confirmation with minitest and getting a 401 response instead of a 200. In the application it works correctly.

# registrations_controller_test.rb  require 'test_helper'    class RegistrationsControllerTest < ActionController::TestCase      def setup      @controller = Users::RegistrationsController.new    end      #Users::RegistrationsController    test 'register new user' do      email = 'register_new_user@test.com'      @request.env["devise.mapping"] = Devise.mappings[:user]      post :create, params: { user: {email: email, password: 'alksdjflksdjfkj'}}        confirm_email = ActionMailer::Base.deliveries.last      u = User.find_by(email: email)        refute u.confirmed?      assert_match "confirmation_token=#{u.confirmation_token}", confirm_email.body.to_s      assert_equal email, confirm_email.to[0]      #/users/confirmation?confirmation_token=shsgqVVV2tayLL9Z139s      #devise/confirmations#show        @controller = Devise::ConfirmationsController.new      @request.env["devise.mapping"] = Devise.mappings[:user]      get "show", params: {confirmation_token: u.confirmation_token}      # response.headers are {"X-Frame-Options"=>"SAMEORIGIN", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "Location"=>"http://test.host/users/sign_in", "Content-Type"=>"text/html; charset=utf-8"}        assert u.confirmed?  #fails      end    end  

After I do get "show", params: {confirmation_token: u.confirmation_token}

The response is a 401 and a redirect to http://test.host/users/sign_in

I'm not sure if this is a routing issue?

rails routes | grep confirmation                 user_confirmation POST     /users/confirmation(.:format)                  devise/confirmations#create             new_user_confirmation GET      /users/confirmation/new(.:format)              devise/confirmations#new                                   GET      /users/confirmation(.:format)                  devise/confirmations#show  

but I noticed response.url is different in test and in my development app:

test: /users?confirmation_token=sxhMSykFUk4VPsxcA6-M
dev: /users/confirmation?confirmation_token=LGoSov1mfaxGu_cpsdnG

Rails HTML Table: <tr> tag doesn't do anything

Posted: 28 Sep 2016 06:50 AM PDT

  <% for ws in @user.workstations %>      <tr class="red">        <td class="td_workstation"> <%= ws.name %> </td>        <td class="td_workstation"> <%= ws.applications %> </td>      </tr>    <% end %>  

The class "red" is supposed to make the background red, but it doesn't do anything. Why isn't it affecting the rows??????

.red {    background: red;    font-size: 60px;  }    .td_workstation, .th_workstation {  border: 1px solid #dddddd;  }  

Data association within a service oriented architecture

Posted: 28 Sep 2016 07:07 AM PDT

We have 3 API applications build as a sort of service oriented architecture. I say sort of because it does not totally embrace the SOA tenets as I'm about to explain with this simple use case.

Use case

We have a Client API which is responsible for handling clients contact information. On the other end, we have a Sales API which take care of quotation and billing. This is the part when it becomes messy (IMHO). The sales API has an orders table which has a client_id attribute in order to know which client is associated to it.

Problem

As I said, the architecture has been built as a sort of SOA, meaning that each service has it's own database. So to continue with our use case, the sales API is storing at some point a client_id, client that does not actually exists in the context of this API because the Client API is the one holding this responsability.

For example, let's say that in order to create a new sales' order, I need to check that the associated client (send as client_id in a POST api.sales.domain.com/orders) actually exists. How to handle such case? For now we do a HTTP request against the Client API and check for a 200 response. What if we want to return embbed client data within an order json:

{      "id": 2,      "status": "pending",      "client": {          "name": "John Doe",          "address": "123 street"      }  }  

As we are using Rails, we use the gem Her in order kinda deal with these cases. But it does not really feel right.

is there a better way to do it?

Why does Rails 5 on Windows 10 run significantly faster than Windows 7?

Posted: 28 Sep 2016 06:26 AM PDT

I switched over to my Windows 10 machine after the Windows 7 one was unavailable, git clone my app and ran rspec in 5 seconds, compared to 17 seconds on Windows 7.

Is there some new feature in Rails 5 that makes it super fast on Windows 10?

Here's my gem file if it helps, I didn't see anything special on it that suggest there was something like Spring.

gem 'rails', '~> 5.0.0', '>= 5.0.0.1'  gem 'pg'  gem 'puma', '~> 3.0'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'coffee-rails', '~> 4.2'  gem 'jquery-rails'  gem 'turbolinks', '~> 5'  gem 'jbuilder', '~> 2.5'    group :test do    gem 'shoulda-matchers', '~> 3.1'    gem 'factory_girl_rails'    gem 'simplecov', :require => false  end    group :development, :test do    gem 'byebug', platform: :mri    gem 'rspec-rails', '~> 3.5'  end    group :development do    gem 'web-console'    gem "better_errors"    gem "binding_of_caller"  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]    gem 'bootstrap-sass', '~> 3.3.6'  gem 'figaro'  gem 'indeed_api'  gem 'nokogiri'  gem 'numbers_in_words'  gem 'pry'  gem 'resque', "~> 1.22.0" # Heroku requires 1.22.0  Read more here: https://devcenter.heroku.com/articles/queuing-ruby-resque  gem 'rake', "~> 11.3.0"  gem 'sinatra', github: 'sinatra/sinatra', branch: 'master' # Specifically for resque front-end    gem 'rails-controller-testing'  

Phusion Passenger shutting down

Posted: 28 Sep 2016 06:23 AM PDT

I am trying to log to STDOUT using APACHE + PASSENGER and i am noticing that passenger gets shutdown after first request. (Signal received. Gracefully shutting down... (send signal 2 more time(s) to force shutdown)).

However, when logging into file, the application works fine.

Any help in clearing this confusion would be highly appreciated!

Thanks in advance.

PS : i am running Apache in foreground and getitng this error :-

[mpm_event:notice] [pid 4249:tid 139620754126656] AH00492: caught SIGWINCH, shutting down gracefully

Unable to autoload constant Api::V1::UsersController

Posted: 28 Sep 2016 06:31 AM PDT

I've been developing API, but when I access the endpoint Unable to autoload constant Api::V1::UsersController, expected /Users/toshikiinami/Desktop/billing/app/controllers/api/v1/users_controller.rb to define it comes out.

  • I use rails 4.2.3

Any ideas to configure the subdomain endpoint properly?

config/routes.rb

Rails.application.routes.draw do        namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/'  do      scope module: :v1 do        resources :users, only: [:index]      end    end  end  

controllers/api/v1/users_controller.rb

class UsersController < ActionController::Base    def index      render 'test' => 'json'    end  end  

/etc/hosts

##  # Host Database  #  # localhost is used to configure the loopback interface  # when the system is booting.  Do not change this entry.  ##  127.0.0.1 localhost  127.0.0.1 api.localhost.local  

undefined method `filter' for #<Class:0x007fc0600be140> edited, need more help please

Posted: 28 Sep 2016 07:45 AM PDT

Please see edit below

I've received precious help from another question but now I have this error undefined methodfilter' for #`

I am trying to filter by categories (Category were created in the console, like Category.create(name: "Ruby") and so on...)

Looking forward for your help, thanks in advance :)

2.3.1 :009 > Category.all    Category Load (0.2ms)  SELECT "categories".* FROM "categories"   => #<ActiveRecord::Relation [#<Category id: 1, name: "Ruby", created_at: "2016-09-26 09:03:17", updated_at: "2016-09-26 09:03:17">, #<Category id: 2, name: "Rails4", created_at: "2016-09-26 09:03:25", updated_at: "2016-09-27 14:32:39">, #<Category id: 3, name: "Rails5", created_at: "2016-09-26 09:03:30", updated_at: "2016-09-27 14:35:25">, #<Category id: 4, name: "Heroku", created_at: "2016-09-26 09:03:35", updated_at: "2016-09-27 14:35:47">, #<Category id: 5, name: "AWS-Amazon", created_at: "2016-09-26 09:03:43", updated_at: "2016-09-26 09:03:43">]>  

my model tuto

class Tuto < ActiveRecord::Base    acts_as_votable    belongs_to :user    belongs_to :category    validates :category_id, presence: true        def self.search(search)      if search        where(["title LIKE ?","%#{search}%"]).order('created_at DESC')      else        all      end    end  #moved this method in category.rb    #def self.filter(filter)      #if filter        #where(["name LIKE ?","%#{filter}%"]).order('created_at DESC')      #else        #all      

Tuesday, September 27, 2016

Using many dynamic Google Maps on modals on the same page - Rails | Fixed issues

Using many dynamic Google Maps on modals on the same page - Rails | Fixed issues


Using many dynamic Google Maps on modals on the same page - Rails

Posted: 27 Sep 2016 07:43 AM PDT

I have a shops page with 12 stores. Each store has a button to show it's individual position on the map. The problem is it's not working (I get the same position on every map, it's supposed to be dynamic).

What I'm doing is loading a map inside the ruby block for each shop (Map is loading 12 times - 12 requests to the Google API):

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBktelhtX7My2gbXhZIR8J9Lu6XXXQ1nNM">  </script>    <script type="text/javascript">      var LocationData = [          [<%= shop.latitude %>, <%= shop.longitude %>, '<%= shop.direction %>']      ];      var map;        function initialize() {          var mapOptions = {              zoom: 3          };          var map = new google.maps.Map(document.getElementById('map-canvas-<%= shop.id %>'),              mapOptions);          var bounds = new google.maps.LatLngBounds();          var infowindow = new google.maps.InfoWindow();              for (var i in LocationData) {              var p = LocationData[i];              var latlng = new google.maps.LatLng(p[0], p[1]);              bounds.extend(latlng);              var image = 'assets/marcador_sushi.png';                var marker = new google.maps.Marker({                  position: latlng,                  icon: image,                  map: map,                  title: p[2]              });                google.maps.event.addListener(marker, 'click', function() {                  infowindow.setContent(this.title);                  infowindow.open(map, this);              });          }            map.fitBounds(bounds);      }        google.maps.event.addDomListener(window, 'load', initialize);  </script>  

Rails scopes with hash syntax

Posted: 27 Sep 2016 07:43 AM PDT

Here are my two models:

class Author < ApplicationRecord    has_many :articles  end    class Article < ApplicationRecord    belongs_to :author    scope :articles_by_author, ->(author_id) {joins(:author).where(author: {id: author_id})}  end  

I am trying to get the Article.articles_by_author(id) scope to work. Basically: It should return all the articles for a particular Author.

Here is what happens:

First I grab an author:

author = Author.first  

Then I run the query:

Article.articles_by_author(author)  

The generated SQL seems right:

SELECT "articles".*   FROM "articles"   INNER JOIN "authors"   ON "authors"."id" = "articles"."author_id"   WHERE "author"."id" = 1  

But it errors out with the following:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: author.id: SELECT "articles".* FROM "articles" INNER JOIN "authors" ON "authors"."id" = "articles"."author_id" WHERE "author"."id" = 1

What am I messing up within this scope? I want to keep the hash syntax within this scope.

Core php for multi-tenant application and recommended php framework which is compatible with php 5.3

Posted: 27 Sep 2016 07:19 AM PDT

I was planning to develop my upcoming multi-tenant application on Laravel but my client's server configuration is just PHP 5.3 and current versions of Laravel do not support PHP 5.3, I also looked for Codeigniter and Yii but their latest versions are also not supporting PHP 5.3 and ofcourse in 2016 no new framework is going to support it but my client can't upgrade it as he has his websites running on it. He is asking me to develop the application on CORE PHP so please I would like to have experts advice will it be a good idea to develop multi-tenant application(separate databases for each customer and single code base for all) on CORE PHP on PHP v5.3? Also, please suggest about Ruby on Rails but there will be a learning curve for me as I have no experience of RoR.

Your suggestions will be highly appreciated.

Thank you.

Can you define multiple actions with the same name in Rails?

Posted: 27 Sep 2016 07:22 AM PDT

In asp.net MVC, you can define multiple action methods with the same name, as long as the arguments (the method signature in other words) is different. Can you do this in Rails, or do you have to settle with switch statements inside the same action?

rake db:migrate error (Migrations are pending)

Posted: 27 Sep 2016 07:16 AM PDT

I have been searching for a solution to my problem and haven't had any luck. I am a beginner following a tutorial and I reached a point where I had to run the command 'rake db:migrate' and keep getting an error.

$ rake db:migrate  == 20160927120721 CreateTodoItems: migrating ==================================  -- create_table(:todo_items)  rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    undefined method `refrences' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x0055d8b19b8298>  Did you mean?  references  /home/paul/todo/db/migrate/20160927120721_create_todo_items.rb:5:in `block in change'  /home/paul/todo/db/migrate/20160927120721_create_todo_items.rb:3:in `change'  NoMethodError: undefined method `refrences' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x0055d8b19b8298>  Did you mean?  references  /home/paul/todo/db/migrate/20160927120721_create_todo_items.rb:5:in `block in change'  /home/paul/todo/db/migrate/20160927120721_create_todo_items.rb:3:in `change'  Tasks: TOP => db:migrate  (See full trace by running task with --trace)  

I have tried to reset the rake with 'rake db:reset' but it tells me that there is a pending migration and to try 'rake db:migrate'. I also tried 'rake db:drop' 'gem update rake' 'bundle update rake' 'bunlde exec rake db:migrate' and still no luck. Can someone assist me with this? I am very new to all of this so if there's anything more I can post please let me know so I can continue to grow and learn! Thanks in advance!!

Ubuntu 16.04LTS
Rails 4.2.6
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]

Error when trying to use ruby gem- NameError (uninitialized constant RightScraper::Scraper)

Posted: 27 Sep 2016 07:44 AM PDT

I am trying to use a ruby gem called right_scraper. I have added the gem to my gem file and it installs fine. I used the example code from the gems github page (https://github.com/rightscale/right_scraper)

require 'rubygems'  require 'right_scraper'    scraper = RightScraper::Scraper.new(:basedir => '/tmp', :kind => :cookbook)  scraper.scrape(:type => :git, :url => 'git://github.com/rightscale/right_scraper.git')  

running this code returns the following error:

NameError (uninitialized constant RightScraper::Scraper)  

Does anyone know whats going wrong?

"undefined method `user' for nil:NilClass"

Posted: 27 Sep 2016 07:13 AM PDT

Hello everyone I am new to rails and for some reason I keep getting an error

"undefined method `user' for nil:NilClass".

I have pasted an image of the error on the bottom and I posted the code below.

-Thank you.

Image Error

Controller (registeredapps_controller) create#action:

class RegisteredappsController < ApplicationController     def create     @registeredapp = Registeredapp.new(registeredapp_params)     @registeredapp.user = current_user      unless RegisteredappPolicy.new(current_user, @registeredapp).create?      flash[:alert] = "not authorized"       redirect_to user_registeredapps_path(current_user.id)    end      if @registeredapp.save      flash[:notice] = "You successfully registered your app."      redirect_to user_registeredapp_path(current_user.id, @registeredapp.id)    else      flash.now[:alert] = "There was an error registering your app. Please try again."      render :new    end  end  

Policies (using Pundit Gem) registeredapp_policy.rb

class RegisteredappPolicy       def initialize(user, registeredapp)      @registeredapp = registeredapp      @user = user    end      def create?      if @user.present?       @user = @registerdapp.user      else       false    end  end  

Here are my models

User.rb

class User < ApplicationRecord      # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable, :confirmable      def avatar_url(size)      gravatar_id = Digest::MD5::hexdigest(self.email).downcase      "http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}"    end      has_many :registeredapps  end  

Registeredapp.rb

class Registeredapp < ApplicationRecord    belongs_to :user    has_many :events  end  

passing jquery dattimepicker to sqlite database in Ruby on Rails

Posted: 27 Sep 2016 07:03 AM PDT

So i have a Jquery DataTimePicker implemented and do not know how to pass this field into my Database.

Just need some basic help, not even sure where to begin. Any help is greatly appreciated

This is what i have as far as code goes.

<div class="field">  <%= f.label :start_date %>  <input id="datetimepicker" type="text" >  <script type="text/javascript">    jQuery('#datetimepicker').datetimepicker();  </script>  </div>  

Using Rails 3.2.22 and Mongoid 2.5.1 with Mongo 3.2

Posted: 27 Sep 2016 06:54 AM PDT

I am attempting to upgrade our legacy rails/mongo application. Our production Mongodb is 2.4 and we would like to upgrade to 3.2 and still use Mongoid. We use auth on the development database as follows

mongo <host> -usome_user -psome_pwd --authenticationDatabase "some-database"  

The Mongoid.yml file for Mongoid 2.5.1 doesn't seem to have the ability to pass the authentication database parameter, and the authentication fails when trying to perform a rake command, or even get into the rails console.

So my question is this, IS there a way to set the default authentication database so that this parameter does not need to be passed along? If not, then is there a way I can edit my 2.5.1 mongoid.yml so include this information? I am guessing the I will have to upgrade the whole nine yards to a version of Mongoid which can support Mongodb 3.2

Below is the pertinent part of the YML file: development: <<: *defaults hosts: - - - - port: database: username: password:<%= SOME_CREDENTIALS[:mongo][:password] %> max_retries_on_connection_failure: 1

Categories Filter doesn't work as expected - Rails 4

Posted: 27 Sep 2016 07:28 AM PDT

In my app you can search a "tuto" by keywords or by category. When a category is selected all the tutos belonging to this category should be displayed... But it doesn't work...( ALL tutos from ALL categories remain displayed...)

What am I missing? Help would be very welcome, thanks in advance.

I've created my categories name in the console like so

Category Load (1.5ms)  SELECT "categories".* FROM "categories"   => #<ActiveRecord::Relation [#<Category id: 1, name: "Ruby", created_at: "2016-09-26 09:03:17", updated_at: "2016-09-26 09:03:17">, #<Category id: 2, name: "Rails 4", created_at: "2016-09-26 09:03:25", updated_at: "2016-09-26 09:03:25">, #<Category id: 3, name: "Rails 5", created_at: "2016-09-26 09:03:30", updated_at: "2016-09-26 09:03:30">, #<Category id: 4, name: "Heroku", created_at: "2016-09-26 09:03:35", updated_at: "2016-09-26 09:03:35">, #<Category id: 5, name: "AWS-Amazon", created_at: "2016-09-26 09:03:43", updated_at: "2016-09-26 09:03:43">]>  2.3.1 :006 >  

Here is my model with the scopes:

class Tuto < ActiveRecord::Base    acts_as_votable    belongs_to :user    belongs_to :category    validates :category_id, presence: true      scope :ruby,   -> { where(category_id: 1)}    scope :rails4, -> { where(category_id: 2)}    scope :rails5, -> { where(category_id: 3)}    scope :heroku, -> { where(category_id: 4)}    scope :aws,    -> { where(category_id: 5)}      def self.search(search)      if search        where(["title LIKE ?","%#{search}%"])      else        all      end    end  end  

my controller, everything happen in the action index

class TutosController < ApplicationController    before_action :authenticate_user!, only: [:new, :create]    before_action :set_tuto, only: [:show, :edit, :update, :destroy, :upvote]        def index      if params[:search]        @tutos = Tuto.search(params[:search]).includes(:user, :category)      else        @tutos = Tuto.all.includes(:user, :category)      end        @categories = if params[:category].present?        case params[:category]        when "ruby"          Category.ruby        when "rails4"          Category.rails4        when "rails5"          Category.rails5        when "heroku"          Category.heroku        when "aws"          Category.aws        else          Category.all        end      end    end        def show      @tuto = Tuto.find(params[:id])      @user = User.all    end      def new      @tuto = Tuto.new    end      def edit    end      def create        @tuto = Tuto.new(tuto_params)      @tuto.user_id = current_user.id        respond_to do |format|        if @tuto.save          flash[:success] = "Test"          format.html { redirect_to @tuto, notice: 'Tuto was successfully created.' }          format.json { render :show, status: :created, location: @tuto }        else          format.html { render :new }          format.json { render json: @tuto.errors, status: :unprocessable_entity }        end      end    end      def update      respond_to do |format|        if @tuto.update(tuto_params)          format.html { redirect_to @tuto, notice: 'Tuto was successfully updated.' }          format.json { render :show, status: :ok, location: @tuto }        else          format.html { render :edit }          format.json { render json: @tuto.errors, status: :unprocessable_entity }        end      end    end        def destroy      @tuto.destroy      respond_to do |format|        format.html { redirect_to tutos_url, notice: 'Tuto was successfully destroyed.' }        format.json { head :no_content }      end    end        def upvote      @tuto.upvote_by current_user      redirect_to :back    end        private          def set_tuto        @tuto = Tuto.find(params[:id])      end        def tuto_params        params.require(:tuto).permit(:title, :content, :id, :user_id, :category_id)      end  end  

EDIT

and the intersting part of my view, index.html.slim

 .container    .row      h1.text-gray Tutorials     .row.search_banner      .col-xs-3        =form_tag tutos_path, :method => 'get' do           =text_field_tag :search, params[:search],  placeholder:"Search by keywords"          =submit_tag "Search", class:'btn btn-xs btn-default btn-search'      .col-xs-3        =form_tag '/tutos', method: 'get' do          = select_tag :category, options_for_select(["ruby", "rails4", "rails5", "heroku", "aws"], :selected => params[:category])                  = submit_tag "Filter", class:"btn btn-xs btn-default btn-search"        .col-xs-3        -if user_signed_in?          = link_to "Create a tuto", new_tuto_path, class:"btn btn-success"        br        br          #tutos.transitions-enabled    -@tutos.each do |tuto|      .box.panel-default        = link_to image_tag(image_by_category(tuto.category.try(:name))), tuto_path(tuto)            h3 = link_to tuto.title, tuto_path(tuto), class:"title-link"             h6           | Created by:          span<>          = tuto.user.full_name        br        span.glyphicon.glyphicon-heart        span<>        = tuto.get_upvotes.size  

In my select tag the Chose a categorydoesn't appear I have rubythat appears first of the list... I found some help on other topics, I believe I messed it a bit...

Access id of nested object after creation

Posted: 27 Sep 2016 07:31 AM PDT

I 'm creating an object through nested attributes in rails and I need to access this object after the creation on the same method.

@contact.update(contact_params)  

This line sometimes creates a child (an address). Is there any way to get the address id if there is one?

Why Ruby (or Rails) do things like this? (Unexpected model methods without "self" behavior)

Posted: 27 Sep 2016 06:56 AM PDT

I've got a validator in ActiveRecord model, in which I faced with some realy strange behavior.

Example:

if status_changed?    p status # output on line below    # <= "my_status_1"    p my_conditions_1 # output on line below    # <= false      if my_conditions_1      errors.add(:status, 'Error1')      status = status_was    end      p status # output on line below    # <= nil      # my_conditions_2 depends on "status variable"    if my_conditions_2      errors.add(:status, 'Error2')      status = 2    end  end  

Second condition always failed, because status somehow was setted to nil. But when I changed status to self.status everything started working as expected.

Can someone explain it? Because I don't really get what's going on here. And I don't want to live in fear of missing self in models.

ruby, send invitation to message [on hold]

Posted: 27 Sep 2016 06:28 AM PDT

I would like to know if it's possible that you help me . I try to create a systeme who enable to send an invitation for speak. i have 1 user A who want to speak with user B User A send an invitation as notification to User B, User B open notification witch return on a page where they have 2 choice possible accept or don't accept if User B accept they can conversation open else invitation DELETE.

So i have create my model "add" "user" " conversation" "notification" i need only a methode for my Add controller for send invitation as notification .

ty.

Cleaning API Controllers by separating Swagger from the controllers

Posted: 27 Sep 2016 07:21 AM PDT

I'm using Swagger as a UI for my rails API. That means that in my API controllers, I have a lot of swagger blocs of code, making my files hard and heavy to read. I'm looking for a way to separate concerns.

This is what I had:

In my controllers/api/v1/stuffs_controller.rb

module Api    module V1      class StuffsController < BaseController        has_scope :by_category, type: :array        has_scope :by_stuff_type, type: :array        has_scope :by_device_type, type: :array        before_action :set_stuff, only: [:show, :like, :unlike, :desire, :undesire]          swagger_controller :stuffs, 'Stuffs'              swagger_api :index do          summary 'Get all the stuffs'          param :query, :by_category, :string, :optionnal, "Category"          param :query, :by_stuff_type, :string, :optionnal, "Stuff Type"          param :query, :by_device_type, :string, :optionnal, "Device Type"          param :query, :s, :array, :optionnal, "Search Terms"        end          def index          render json: collection, each_serializer: Api::V1::Stuff::IndexSerializer, include: ['categories', 'users.devices', 'stuffs.categories', 'user', 'user.devices.device_model'], status: 200, root: nil        end        end    end  end  

And it's like that for every action in every controller :s

I tried creating modules to encapsulate Swagger UI logic and clean up a little bit my controllers. This is what I came up with (that doesn't work):

In controllers/api/v1/stuffs_controller.rb:

module Api    module V1      class StuffsController < BaseController        include SwaggerStuffs          has_scope :by_category, type: :array        has_scope :by_stuff_type, type: :array        has_scope :by_device_type, type: :array        before_action :set_stuff, only: [:show, :like, :unlike, :desire, :undesire]          swagger_controller :stuffs, 'Stuffs'              SwaggerStuffs.call_index        def index          render json: collection, each_serializer: Api::V1::Stuff::IndexSerializer, include: ['categories', 'users.devices', 'stuffs.categories', 'user', 'user.devices.device_model'], status: 200, root: nil        end        end    end  end  

Then in lib/swagger_modules/recipes_controller_module.rb:

module SwaggerStuffs    def self.call_index      swagger_api :index do        summary 'Get all the stuffs'        param :query, :by_category, :string, :optionnal, "Category"        param :query, :by_stuff_type, :string, :optionnal, "Stuff Type"        param :query, :by_device_type, :string, :optionnal, "Device Type"        param :query, :s, :array, :optionnal, "Search Terms"      end    end  end  

This produces the following error when I try to use swagger UI or restart the server:

uninitialized constant Api::V1::StuffsController::SwaggerStuffs (NameError)  

I added config.autoload_paths += %W(#{config.root}/lib) in my config/application.rb file, but the same error appears.

Is there something I am missing ? Is it a good practice to separate swagger logic from my controllers ?

Thanks :)

Bootsy rails gem not showing images in production

Posted: 27 Sep 2016 06:22 AM PDT

I'm using bootsy (https://github.com/volmer/bootsy) to make formatting my Blog article body much easier. When I upload files in the WYSIWYG editor locally I can view them later just fine; however, when I am in production and do this all the img tags link to

/uploads/bootsy/image/1/image_name.jpeg  

Instead, the path should be a aws s3 url. I am using s3 with carrierwave = for some other things (the post main image url), and I'm not having any problems. I imagine there is some kind of config I need to do to work in production.

Remove devise email validation

Posted: 27 Sep 2016 06:09 AM PDT

I use devise and devise-token-auth. I have User model with following content

class User < ApplicationRecord      devise :database_authenticatable, :registerable,            :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]    include DeviseTokenAuth::Concerns::User      validates_uniqueness_of :login    validates_presence_of :full_name      protected    def email_required?      puts "email_required called"      false    end  end  

but devise email validation is still working

2.3.0 :003 > user = User.new(login: "hello", password: "11111111", password_confirmation: "11111111", full_name: "hello world")   => #<User id: nil, provider: "email", uid: "", email: nil, full_name: "hello world", login: "hello", created_at: nil, updated_at: nil>   2.3.0 :004 > user.valid?  email_required? called   #<===== my method is called!     (3.7ms)  SELECT COUNT(*) FROM "users" WHERE "users"."provider" = $1 AND "users"."email" IS NULL  [["provider", "email"]]    User Exists (1.0ms)  SELECT  1 AS one FROM "users" WHERE "users"."login" = $1 LIMIT $2  [["login", "hello"], ["LIMIT", 1]]   => false   2.3.0 :005 > user.errors   => #<ActiveModel::Errors:0x000000028e2338 @messages={:email=>[...]}, @details={:email=>[{:error=>:blank}]}>  

Why this? Thanks

Rails - Stripe::InvalidRequestError in Bookings#new Must provide source or customer

Posted: 27 Sep 2016 06:06 AM PDT

I'm getting the above error in my Rails app. I have the following Stripe code in my Booking model -

begin    charge = Stripe::Charge.create(      amount: total_amount,      currency: "gbp",      source: self.stripe_token,       description: "Booking created for amount #{total_amount}")    self.stripe_charge_id = charge.id    save!    rescue Stripe::CardError => e    errors.add(:base, e.message)    false  end  

I don't understand why I'm getting the error when I'm clearly including source within my stripe code. I've expressed it above as self.stripe_token but I've tried just stripe_token but still get the same error. My understanding is I need to provide either source or customer, not both, and that it needs to be source rather than customer.

What am I missing?

Devise error - ActionController::InvalidAuthenticityToken

Posted: 27 Sep 2016 05:59 AM PDT

Got problem in devise logout while admin and user logged in same page

For example i logged as user in chrome browser and logged as admin in the same browser,when i logged out of admin session the user session is automatically logged out and redirect to sign in page.
When i try to login as user it's successfully logged in and goes to the admin login page and try to log-in it shows -

ActionController::InvalidAuthenticityToken  

Gitlab CE 8.9 to 8.10 Upgrade Failed

Posted: 27 Sep 2016 05:51 AM PDT

I've been updating my server through the newer GitLab versions, I was at 6.7 yesterday in the evening, and currently I'm up to 8.10.

Currently when starting the GitLab service, Sidekiq fails with "Could not find ace-rails-ap-4.1.0 in any of the sources". I've done all that I can to verify that that gem exists in the vendor sources along with gitlab, but no luck. log/sidekiq.log is as follows:

/usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find ace-rails-ap-4.1.0 in any of the sources (Bundler::GemNotFound)      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/spec_set.rb:85:in `map!'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/spec_set.rb:85:in `materialize'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/definition.rb:114:in `specs'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/definition.rb:159:in `specs_for'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/definition.rb:148:in `requested_specs'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/environment.rb:18:in `requested_specs'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/runtime.rb:13:in `setup'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler.rb:120:in `setup'      from /usr/local/rvm/gems/ruby-2.1.5/gems/bundler-1.3.5/lib/bundler/setup.rb:17:in `<top (required)>'      from /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'      from /usr/local/rvm/rubies/ruby-2.1.5/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'  

Using Ruby 2.3.1, Ubuntu 14.04.

Postgres: What does @@ mean?

Posted: 27 Sep 2016 07:17 AM PDT

Recently I've found a piece of code for ruby on rails which should search string like like-operator:

scope :search, -> (query) { where('name @@ :q', q: query) }  

But couldn't find any documentation about it.

The operator doesn't work as expected. So what exactly it does?

Change ActiveRecord error blank message for all models

Posted: 27 Sep 2016 05:34 AM PDT

I know that custom error message can be added in locale .yml file like this:

    errors:        models:          user:            attributes:              name:                blank: "The field is required"  

How do I change error blank message for all the models at a time?

Find count of predefined words using active record or pure postgres query

Posted: 27 Sep 2016 05:43 AM PDT

I want to get some text analysis. As a result I want to get count of some key words in all records like this:

answer id: 1, text: 'some good text'

answer id: 2, text: 'some really bad text, angry angry angry text'

and result should be like this:

good: 1, bad: 1, angry: 3

I don't want to select all records and then map them count this key words on ruby etc because of big amount of data. Also I find some solution:

Answer.pluck('regexp_matches(text, \'\mMyKeyword\M\', \'gi\')').flatten.count

Works fine for 1 keyword. This causes problem that I used to do database request per keyword. I'm using rails 4 and potgres. Any help appreciated

Ruby on Rails rmagick Error

Posted: 27 Sep 2016 07:17 AM PDT

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        /home/indiba3/.rvm/rubies/ruby-2.1.8/bin/ruby -r ./siteconf20160927-26485-11i89l1.rb extconf.rb  checking for gcc... yes  checking for Magick-config... no  checking for pkg-config... yes  Package MagickCore was not found in the pkg-config search path.  Perhaps you should add the directory containing `MagickCore.pc'  to the PKG_CONFIG_PATH environment variable  No package 'MagickCore' found  checking for outdated ImageMagick version (<= 6.4.9)... *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:      --with-opt-dir      --without-opt-dir      --with-opt-include      --without-opt-include=${opt-dir}/include      --with-opt-lib      --without-opt-lib=${opt-dir}/lib      --with-make-prog      --without-make-prog      --srcdir=.      --curdir      --ruby=/home/indiba3/.rvm/rubies/ruby-2.1.8/bin/ruby    extconf failed, exit code 1    Gem files will remain installed in /home/indiba3/.rvm/gems/ruby-2.1.8/gems/rmagick-2.15.4 for inspection.  Results logged to /home/indiba3/.rvm/gems/ruby-2.1.8/extensions/x86-linux/2.1.0/rmagick-2.15.4/gem_make.out    An error occurred while installing rmagick (2.15.4), and Bundler cannot continue.  Make sure that `gem install rmagick -v '2.15.4'` succeeds before bundling.  

My Ruby Version is:ruby-2.1.8 [ i686 ] Rails Version is: 4.2.4

I have cloned a new project.Whenever i run bundle install command i get the above error.Because of this error i'm unable to run my project.So pls help.

Speed up rake task by using typhoeus

Posted: 27 Sep 2016 05:12 AM PDT

So i stumbled across this: https://github.com/typhoeus/typhoeus

I'm wondering if this is what i need to speed up my rake task

Event.all.each do |row|      begin    url = urlhere + row.first + row.second    doc = Nokogiri::HTML(open(url))    doc.css('.table__row--event').each do |tablerow|      table = tablerow.css('.table__cell__body--location').css('h4').text      next unless table == row.eventvenuename        tablerow.css('.table__cell__body--availability').each do |button|          buttonurl = button.css('a')[0]['href']          if buttonurl.include? '/checkout/external'            else          row.update(row: buttonurl)        end        end    end    rescue Faraday::ConnectionFailed      puts "connection failed"    next    end  end  

I'm wondering if this would speed it up, Or because i'm doing a .each it wouldn't?

If it would could you provide an example?

Sam

Querying Postgres Table with JSONB data

Posted: 27 Sep 2016 05:04 AM PDT

I have a Table which stores data in a JSONB column.

Now, what i want to do is, query that table, and fetch records, which have specific values for a key.

This works fine:

SELECT "documents".*  FROM "documents"  WHERE (data @> '{"type": "foo"}')  

But what i want to do is, fetch all the rows in the table, which have types foo OR bar.

I tried this:

SELECT "documents".*  FROM "documents"  WHERE (data @> '{"type": ["foo", "bar"]}')  

But this doesn't seem to work.

I also tried this:

SELECT "documents".*  FROM "documents"  WHERE (data->'type' ?| array['foo', 'bar'])  

Which works, but if I specify a key like so data->'type' it takes away the dynamicity of the query.

BTW, I am using Ruby on Rails with Postgres, so all the queries are going through ActiveRecord.

Rails 4.1: Spacing Issues when using HAML

Posted: 27 Sep 2016 07:26 AM PDT

enter image description hereFirst time HAML wth Ruby on Rails , I want to align the average no of comments with the months. So the first one aligns but not the rest.

screenshot of table so far

monthly.stats.html.haml

.row    .col-md-3      Month    .col-md-9      - 6.times.reverse_each do |i|        %th= i.month.ago.strftime('%b %y')        %tr          - 6.times do            %td &nbsp;        .col-md-3      Av. No of Comments    .col-md-9      - 6.times.reverse_each do |i|        %tr #{@monitor.average_number_of_comments(i.months.ago, Time.now)}        %tr          - 6.times do            %td &nbsp;

I am using

%tr    - 6.times do      %td &nbsp;  

for spaces but this is not spacing correctly

Is there any difference between '/' and '' routes?

Posted: 27 Sep 2016 05:28 AM PDT

Is there a difference between these 2 Rails routes:

get '/', to: 'demo#index'  

vs.

get '', to: 'demo#index'  

Both seem to match the root.

How to internationalise jQuery DataTables in Rails 4 app

Posted: 27 Sep 2016 05:13 AM PDT

in order to display some data we use jQuery datatables. So far we implemented full internationalisation of our app (I18n) except for table features like pagination or search bar descriptions. I don't seem to fully understand the way I18n works and on which event I would have to update the link to the DataTables localisation JSON in order to dynamically update the language property of my DataTable object. I tried the following...

  // Global variable to track localisation path state    var json_for_current_locale = localisation_json_url();      // Hardcoded mappings of Rails locale codes to DataTable language names    function locale_to_language(locale) {      language_codes = {        "en": "English",        "de": "German"      };      return language_codes[locale]    }      function localisation_json_url() {      return 'https://cdn.datatables.net/plug-ins/1.10.12/i18n/' + locale_to_language("<%= I18n.locale %>") + '.json';    }      jQuery('<WHAT TO CAPTURE HERE?>').<WHAT EVENT TO LISTEN TO HERE?>(..., function(){      json_for_current_locale = localisation_json_url();    });      jQuery('#places').DataTable({      "language": { "url": json_for_current_locale },      "pageLength": 50,      "columnDefs": [        {          "targets": [ 0 ],          "sortable": false,          "searchable": false        },        {          "targets": [ 3 ],          "sortable": false,        }      ]    });  

I hope the problem is described appropriately. Thanks for any hints!

best Andi

Ruby on Rails 5 : how to create a web service delivering nested attributes?

Posted: 27 Sep 2016 05:45 AM PDT

I am developing a RoR5 application to provide crypto keys to various applications, through a web service. My RoR application manages Users, and nested Ciphers (using nested attributes). A cipher has a name, and a value (string).

I wish to expose a web service to deliver the requested key:

1 - The client application provides a User and a Cipher name to the web service

2 - The web service returns the Cipher value

I am not expert in RoR, but I have the intuition that I should start by defining a new route for this service. Here is the current routes.rb:

Rails.application.routes.draw do    get 'sessions/new'      root   'sessions#new'    get    '/login',   to: 'sessions#new'    post   '/login',   to: 'sessions#create'    delete '/logout',  to: 'sessions#destroy'    resources :users  end  

Hints on how to structure the application and references are welcome !

Rails 4,Setting up CSS Background Image

Posted: 27 Sep 2016 05:20 AM PDT

I want to set a background image via CSS background: url() property. But it doesn't working. There is nothing special. I have done;

-rails new myApp  -rails g controller Welcome index.  

Thats it. I have this div <div class="image">

And the css for it.

.image{      background: url('image.jgp');  }    

I have image.jgp on my assets/images folder.I can do <%= image_tag('assets/image.jgp') and it works.But CSS part doesn't.` How this problem could be solved?