Friday, December 23, 2016

Rails Devise disable redirect for ajax request | Fixed issues

Rails Devise disable redirect for ajax request | Fixed issues


Rails Devise disable redirect for ajax request

Posted: 23 Dec 2016 07:56 AM PST

I want for one of the pages of the application has the ability to partially update some user settings. Also the application already has a page to edit all settings I was faced with the fact that when I send a request for a partial update, the devise redirects me to the root, but I don`t want it.

Can I somehow disable redirection for the Ajax request, and leave for a page to edit all settings? Or at least turn it off for all pages at once?

Rails keep form data in session using devise

Posted: 23 Dec 2016 07:54 AM PST

I added custom field to devise registration form : radio button and select list the problem I have is that if there is an error while validating data (for example the user wrote the password wrong) I will be redirected to registration form , the custom fields will loose the data. The example is explained in those 2 pictures :

Before submitting data

After submitting data

Like in the two pictures the user should click again the radio button to select a value , normally it should be saved in session by devise.

I found a solution in stackoverflow here but I coudn't make it work with devise I generated already devise controllers but the solution dosen't work for me. Keep form fields filled after an error (RoR)

How upload image to current folder from json using Carrierwave?

Posted: 23 Dec 2016 07:43 AM PST

I get json file.

[{"fabric_id":"25267","title":"Decora 30100 col.110 (300cm)","image":"example.com/path/30100-110.jpg","images":{"1":"example.com/path/30100-111.jpg","2":"example.com/path/30100-112.jpg"},"price":975,"quantity":"31.4"}...]  

I save new fabrics in DB:

#services/shop/fabrics_syncher.rb   require 'open-uri'  require 'net/http'  require 'json'    class Shop::FabricSyncher    URL = "#"    PHOTO_DIR = "#{Rails.root}/public/uploaders/fabrics"      fabrics = []     shade_fabrics = []      def initialize      uri = URI(URL)      response = Net::HTTP.get(uri)      @fabrics_hash = JSON.parse(response)    end        def sync      @log = Logger.new("#{Rails.root}/log/fabrics_syncher/#{@identifier}-" + Time.now.strftime("%d-%m-%Y-%T") + ".log")      @log.info "log text. URL: #{@url}."  @fabric_hash['fabrics'].each |fabric| do        unless Shop::Fabric.exist?(fabric['fabric_id'])          Shop::Fabric.create(id: fabric['fabric_id'], title: fabric['title'], image: path/mycurent_folder/example.jpg)        end        end  

I need download images from url in current folder publics/upload/fabrics/ in project. I installed gem carrierwave. How can unload images by url to my folder with carrierwave?

Can you show example who can i do it? Thank you

angular modules not injecting

Posted: 23 Dec 2016 07:20 AM PST

my app runs fine in development or test mode, whatever rails s does, but does not work when i run in production mode i get the following errors in my browser

X GET http://localhost:4000/assets/application-bee14c2d11d9c46d50378b54dd87850181256a24c05d6ed2e72c0487fc775f86.js  X GET http://localhost:4000/assets/application-c7fa74d0d86da1dddcd65188a0ad91600d0d55a1be66ba476307822b2d36848b.css  

(also can't run on port 3000 for some reason but lsof -i tcp:3000 yields nothing, maybe this is related? i get

Exiting  /Users/jrogers2/.rvm/gems/ruby-2.2.3/gems/puma-3.6.2/lib/puma/binder.rb:266:in 'initialize': Address already in use - bind(2) for "::1" port 3000 (Errno::EADDRINUSE)      from /Users/jrogers2/.rvm/gems/ruby-2.2.3/gems/puma-3.6.2/lib/puma/binder.rb:26  

)

i've been told it's a manual dependency injection problem but am unconvinced as i've looked around a lot and tried many different formats. but here's some examples of my code anyways and full repo below.

// app.js  (function(){    'use strict';    angular      .module('app', ['templates', 'ui.router', 'Devise', 'ngResource', 'ngMessages', 'infinite-scroll', 'ngFileUpload'])      .run(['Auth', function(Auth){        Auth.currentUser()      }])  }())    //application.js  //= require jquery  //= require angular  //= require angular-devise  //= require angular-messages  //= require angular-ui-router  //= require angular-resource  //= require bootstrap-sprockets  //= require moment  //= require angular-rails-templates  //= require ngInfiniteScroll  //= require ng-file-upload  //= require ng-file-upload-shim  //= require_tree .    // routes.js  (function(){    'use strict';    angular      .module('app')      .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){        $stateProvider          .state('login', {            url: '/',            templateUrl: 'views/login.html',            controller: 'loginController as loginCtrl',            onEnter: ['$state', 'Auth', function($state, Auth){              Auth.currentUser().then(function(data){                $state.go('list', {id: data.list.id})              })            }]          })        $stateProvider          .state('userPurchases', {            url: '/users/:id/purchases',            templateUrl: 'views/purchases.html',            controller: 'purchaseController as purchaseCtrl',            onEnter: ['$state', 'Auth', function($state, Auth){              if (!Auth._currentUser){                $state.go('login')              }            }]          })    // listController.js  (function(){    'use strict';    var listController = ['$scope', 'Auth', '$stateParams', 'itemFactory', 'listFactory', function($scope, Auth, $stateParams, itemFactory, listFactory){      var listCtrl = this;      Auth.currentUser().then(function(data){        $scope.currentUser = data;      });      $scope.itemsCounter = 0;      $scope.list = listFactory.get({id: $stateParams.id});      $scope.items = [];      $scope.createItem = function(input){        input.plzrender = 'list';        input.items.list_id = $scope.currentUser.list.id;        itemFactory.save(input).$promise.then(function(response){          $scope.list = response;        });      }      $scope.deleteItem = function(item){        item.plzrender = 'list';        itemFactory.delete(item).$promise.then(function(response){          $scope.list = response;        });      }      $scope.disableInfinite = false;      $scope.loadMore = function(list){        if ($scope.list.$resolved) {          for (var i = 0; i < 10; i++) {            $scope.items.push($scope.list.items[$scope.itemsCounter]);            $scope.itemsCounter += 1;            if ($scope.itemsCounter >= $scope.list.items.length) {              $scope.disableInfinite = true;              break;            }          }        }      }      $scope.list.$promise.then(function(response){        $scope.loadMore();      });    }];    angular      .module('app')      .controller('listController', listController)  }())  

github repo: https://github.com/jd2rogers2/presently

Audit deep associations with Rails Audited gem

Posted: 23 Dec 2016 07:06 AM PST

I have the next three models:

class School < ActiveRecord::Base    audited    has_associated_audits      has_many :subjects, dependent: :destroy  end    class Subject < ActiveRecord::Base    audited associated_with: :school    has_associated_audits      has_many :attachments, as: :attachable, dependent: :destroy  end    class Attachment < ActiveRecord::Base    audited associated_with: :attachable    belongs_to :attachable, polymorphic: true  end  

Basically, A school has many subjects, and each subject has many attachments (the attachment model is polymorphic because it's used for other models too, just in case it matters...)

The problem is that the audit is not working as I expect. I create a school, then a subject for that school, and then I add attachments to that subject. This is what I get from the console:

School.last.associated_audits # => returns only changes on Subjects, not on subject's attachments.  Subject.last.associated_audits # => returns only changes associated to its attachments  

But I would need is School.last.associated_audits to include attachments audited changes too.

Any ideas?

Like button likes all posts

Posted: 23 Dec 2016 07:13 AM PST

I've implemented a like/unlike function in my app. On the show page for an item, you can like/unlike without any issues. On a user's profile page though, where it lists all the foods they've uploaded, I have two issues: First, when I click the like button for one food, it triggers it for every food and then the button text under every food says "unlike this food", instead of only having the button text change for just the food that was clicked on. The like gets saved to the db for the correct food, but obviously I don't want the button text to change for foods that I haven't liked. Second, when I try to like a different food on the page without refreshing, the liked gets saved in the db as the original food that I clicked on, instead of the one I actually clicked on.

users.show.html.erb    <% @user.foods.each do |food| %>      <div class="row col-md-12">          <div class="food col-md-4">              <h3 class="title"><%= link_to food.title.capitalize, food_path(food.id) %></h3>              <%= link_to (image_tag (food.image.url)), food_path(food.id) %>              <%= render 'shared/vote_form', :food => food %>                <%= link_to pluralize(food.votes.count, "person"), user_votes_path(:user_id => current_user.id, :food_id => food.id) %> <%= food.votes.count == 1 ? 'wants' : 'want' %> to gobble this          </div>            <div class="description col-md-6">          <% if @user.id == current_user.id %>                    <% if food.description.length == 0 %>                      <p><%= link_to "Add Description", edit_food_path(food) %></p>                     <% else %>                      <p><%= food.description %><p>              <p><%= link_to "Edit Description", edit_food_path(food) %></p>                  <% end %>              <% if food.recipe.length == 0 %>              <p><%= link_to "Add Recipe", edit_food_path(food) %></p>            <% end %>            <% else %>              <% if food.description.length == 0 %>              <p>No Description</p>             <% else %>              <p><%= food.description %><p>            <% end %>              <% if food.recipe.length == 0 %>              <p>No Recipe</p>            <% else %>              <p><%= link_to "View Recipe", food_path(food) %></p>              <% end %>            <% end %>          </div>      </div>  <% end %>  

votes controller

class VotesController < ApplicationController      def index      @votes = Food.find(params[:food_id]).votes    end      def new      @vote = current_user.votes.new    end      def create      @user = current_user      @vote = current_user.votes.build(vote_params)          if @vote.save!        @food = @vote.food        respond_to do |format|          format.html {redirect_to :back, notice: "Liked!"}          format.js          end          puts @vote.food.id      else        puts "No"        redirect_back(fallback_location: root_path)      end    end      def show      @user = current_user      @vote = Vote.find(params[:id])    end      def destroy      @vote = Vote.find(params[:id])      @food = @vote.food        if @vote.destroy!        respond_to do |format|          format.html {redirect_to :back, notice: "Unliked!"}          format.js         end      else        puts "NOOOOOO"      end    end      private      def vote_params      params.require(:vote).permit(:food_id)    end  end  

vote partial    <% unless current_user.votes.pluck(:food_id).include?(food.id) %>      <%= button_to "Like This Food", user_votes_path(current_user, { vote: { food_id: food.id } }), :remote => true %>  <% else %>      <% vote = food.votes.where(user_id: current_user.id).first %>      <%= button_to "Unlike This Food", user_vote_path(current_user, vote), :remote => true, method: "delete" %>  <% end %>  

create.js.erb    $('.button_to').replaceWith("<%= j (render :partial => 'shared/vote_form', :locals => { :food => @food, :food_id => @food.id }) %>");  

destroy.js.erb    $('.button_to').replaceWith("<%= j (render :partial => 'shared/vote_form', :locals => { :food => @food }) %>");  

Rails Mysql View to multi tables and search

Posted: 23 Dec 2016 07:49 AM PST

I am looking for a way to create database view to multiple mysql tables. I did not find any way to generate a model with rails. This will be used for searching multiple tables and display the result in a listbox. No update or delete or other function is needed. My understanding is to create the view directly with mysql. Than generate an empty model with rails. But is there another possibility? Situation:

Class Dbtabelle1 < ActiveRecord::Base  end  

This one has the following db-fields: id, fldname, fldtext, fld_fld1, fld_fld2

Class Dbtabelle2 < ActiveRecord::Base  end  

This one has the following db-fields: id, fldname, fldtext, fld_fld4, fld_fld5

Class Dbtabelle3 < ActiveRecord::Base  end  

This one has the following db-fields: id, fldname, fldtext, fld_fld3, fld_fld2

Now I want to have rails through a generator to create a VIEW (talking about database view), that contains the fields with the same name from all three tables and a field that stores the Dbtabelle-name. View should have the fields: id, fldname, fldtext, flddbtabelle

flddbtabelle can be identified and populated by the first two char of the name field. That will be simple sql logic. I am looking for the creation of the view.

How can I get that done all with rails?

Next question is: how do I address data from a db view, that I have only an empty model for?

Using Ruby 2.2.4 and Rails 4.2.7

Can Polymer-Rails work with a Rails Engine?

Posted: 23 Dec 2016 06:54 AM PST

I am working within a Rails Engine for a new project and want to install polymer-rails and create custom elements within the engine app. Upon running rails g polymer:install it installs to /test/dummy/app/assets and /test/dummy/vendor, instead of /app/assets and /vendor. That said, this is my first time working with Rails Engine, and perhaps there's a config outside of your gem that I'm missing.

Any help is much appreciated. :)

Using Social Media Signup in Ruby on Rails

Posted: 23 Dec 2016 06:43 AM PST

I am looking for including a feature so my users can signup even using their gmail, facebook, twitter or any similar IDs.

Would JANRAIN works? I am free to consider even the paid options but prefer to go with a free one.

If anyone could help.

Akbar

How to hightlights by albino and nokogiri? Why my code doesn't work?

Posted: 23 Dec 2016 06:00 AM PST

I follow at Railscasts #272 Markdown With Redcarpet. https://www.youtube.com/watch?v=vPW6t-r0x

At first, I installed python-setuptools:

sudo apt-get install python-setuptools  

then

sudo easy_install pygments  

view/posts/show.html.erb:

<blockquote><h4><%= markdown(@post.content) %></h4></blockquote>  

application_helper.rb:

I wrote this method. It works.

def markdown(text)      markdown =        Redcarpet::Markdown.new(                                Redcarpet::Render::HTML,                                fenced_code_block: true,                                underline:         true,                                quote:             true,                                highlight:         true,                                autolink:          true,                                tables:            true,                                hard_wrap:         true,                                filter_html:       true                                )          syntax_highlighter(markdown.render(text)).html_safe    end  

Then I wrote:

  def syntax_highlighter(html)      doc = Nokogiri::HTML(html)        doc.search("//pre[@lang]").each do |pre|          pre.replace Albino.colorize(pre.text.rstrip, pre[:lang])        end      doc.to_s    end  

It doesn't works. Why?

Replacing high cpu usage rake tasks with another programming language [on hold]

Posted: 23 Dec 2016 05:35 AM PST

I have a rails app that has several rake tasks that run every 15 minutes parsing xml files and adding data from them into the database. These take tasks can sometimes hit 80% cpu on our VPS and I was thinking that replacing them with a compiled language like rust could speed them up.

I was wondering how I would go about adding in another language into a rails app im guessing the biggest problem I would have is I cant have all the model stuff from the rails application in another language. In my case I think I would only be able to do the xml parsing in a compiled language and pass the results to ruby to add into the db.

Is there any way to integrate other languages into a rails app?

Summing the sub values of an indexed hash

Posted: 23 Dec 2016 05:38 AM PST

so I'm working on a project where I have a hash as follows:

{ 1=>{:id=>133,        :total=>#<BigDecimal:cc08558,'0.41323E3',18(18)>},     2=>{:id=>134,         :total=>#<BigDecimal:cc082b0,'0.523E1',18(18)>},     6=>{:id=>166,         :total=>#<BigDecimal:cbdbb98,'0.837E2',18(18)>},     8=>{:id=>168,         :total=>#<BigDecimal:cbdb8a0,'0.72236E3',18(18)>},     9=>{:id=>169,         :total=>#<BigDecimal:cbdb738,'0.132E3',9(18)>} }  

and I want to add element to this hash that has the sum of all the total values in the hash. With the result being as follows:

{ 1=>{:id=>133,        :total=>#<BigDecimal:cc08558,'0.41323E3',18(18)>},     2=>{:id=>134,         :total=>#<BigDecimal:cc082b0,'0.523E1',18(18)>},     6=>{:id=>166,         :total=>#<BigDecimal:cbdbb98,'0.837E2',18(18)>},     8=>{:id=>168,         :total=>#<BigDecimal:cbdb8a0,'0.72236E3',18(18)>},     9=>{:id=>169,         :total=>#<BigDecimal:cbdb738,'0.132E3',9(18)>},    0=>{:id=>000,        :total=><whatever the total is>} }  

but I'm having some trouble getting this done at the moment I have:

month_hash.each.sum(:total)  

But this doesn't seem to be doing what I want.

Any help would be greatly appreciated.

Kaminari problems while upgrading to Rails 5

Posted: 23 Dec 2016 07:05 AM PST

We are upgrading a rails app from v3 to v5 and are using ActiveAdmin which has a dependency on Kaminari. In this process we had to change all our models to inherit from ApplicationRecord instead of ActiveRecord::Base. This change results in the following errors:

undefined method `per_page_kaminari' for #Team::ActiveRecord_Relation:0x00555f215eb200  

where Team is a model that was previously inheriting from ActiveRecord::Base and was changed to inherit from ApplicationRecord. Any help to fix this would be much appreciated.

How to test pdf content generated by prawn-table

Posted: 23 Dec 2016 04:03 AM PST

pdf-inspector provides some useful methods for testing PDFs generated by Prawn. While testing strings is straightforward, I need a way to test that tables (generated by prawn-table) are generated correctly.

For example, I'm generating a table

rows = ['Name','Value']  @objects.each do |object|  rows << [object.name, object.value]  table(rows)  

I would like to include something like the following in a test

let(:object} { create :object, name: 'Object', value: 10 }  let(:my_pdf) { MyPdf.new( #params ) }    it { expect(PDF::Inspector::Text.analyze( my_pdf ).strings ).to include "Object 10" }  

This does not work because prawn-table does not generate this as a single string, but as "Object", "10".

Are there any libraries out there that people recommend for testing content generated by prawn-table. Or is there a standard way to do this?

Resize image does gives no method error carrierwave

Posted: 23 Dec 2016 04:40 AM PST

I am trying to have different versions of the uploaded image with different resolutions. Here is the model in which I am mounting carrierwave uploader

 class Offer < ActiveRecord::Base      mount_uploader :image, ResizeUploader   end  

Here is the mounting model

class ResizeUploader < CarrierWave::Uploader::Base      # Include RMagick or MiniMagick support:    include CarrierWave::MiniMagick    # include CarrierWave::MiniMagick      # Choose what kind of storage to use for this uploader:    #storage :file    storage :fog      process resize_to_fit: [800, 800]      version :tablet do      process resize_to_fill: [200,200]    end        version :thumb do      process resize_to_fill: [280, 280]    end          # Override the directory where uploaded files will be stored.    # This is a sensible default for uploaders that are meant to be mounted:    def store_dir      "uploads/#{model.class.to_s.split("::").last.downcase}/#{mounted_as}/#{model.id}"    end      # Provide a default URL as a default if there hasn't been a file uploaded:    # def default_url    #   # For Rails 3.1+ asset pipeline compatibility:    #   # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))    #    #   "/images/fallback/" + [version_name, "default.png"].compact.join('_')    # end        # Process files as they are uploaded:    # process :scale => [200, 300]    #    # def scale(width, height)    #   # do something    # end      # Create different versions of your uploaded files:    # version :thumb do    #   process :resize_to_fit => [50, 50]    # end      # Add a white list of extensions which are allowed to be uploaded.    # For images you might use something like this:    def extension_white_list      %w(pdf doc xdoc jpg jpeg gif png)    end      # Override the filename of the uploaded files:    # Avoid using model.id or version_name here, see uploader/store.rb for details.    # def filename    #   "something.jpg" if original_filename    # end    end  

The Offer.last.thumb.url gives me no method error. Should I need to have a column named thumb in my offer? What am I missing here?

Configuring before process hook for rollbar gem on initializer does not support method before_process

Posted: 23 Dec 2016 03:14 AM PST

My rollbar gem (1.2.13) initializer setup:

Rollbar.configure do |config|    config.before_process << handler  end  

This config is raising no method error. Any one could report a success case or any tip?

undefined method 'before_process' for #<Rollbar::Configuration:0x007f34b6a4d6b0> (NoMethodError)

What is recommended to use for generating documenation and tests for REST API, preferably in one fell swoop?

Posted: 23 Dec 2016 07:16 AM PST

I have a website in Rails with REST API. I need a) create tests for it b) create documentation for REST API. I can do that in the straightforward way by a) rspec -- tests b) swagger - documentation.

But maybe there's a better way? I need a quite simple solution, I don't want to install, setup and learn a lot of stuff.

how to remove get request in kaminari pagination?

Posted: 23 Dec 2016 03:33 AM PST

Now I have pagination slug like this:

/catalog?page=5 but /catalog/page5 is needed.

Thank you!

Rails devise: create association on user sign_up

Posted: 23 Dec 2016 03:19 AM PST

As a total Ruby noob i need to do a simple thing but doing it the ruby way is not clear for me.

What is want to do is the following:

I have a devise User model with a one to one association "Account"

In the devise registration view i want to add extra form fields for this account, and that is where i am stuck.

It seems i cannot add the account fields to the view

for example this will not work:

# address is a field of Account  <%= f.text_field :address %>  

How can i bring the Account model into the scope? Or is there a way to do something like this

<%= f.text_field :account['address'] %>  

I have really no clue how to add account into scope or how i can access the User assoc Account properly.

Thx for the help

Adjust the line in Ruby [on hold]

Posted: 23 Dec 2016 01:54 AM PST

This below is program in view.

         <p><%= simple_format(h @asking.content ) %></p>  

I want to adjust the line.Now, My view shows with a single line if I post @asking.content with 800 words.(asking model has content column.) Please tell me how to separate line.

wrong number of arguments (0 for 1..4)

Posted: 23 Dec 2016 02:12 AM PST

I am running this code https://github.com/activerecord-hackery/ransack_demo but getting this error

enter image description here

The file is https://github.com/activerecord-hackery/ransack_demo/blob/master/app/views/users/index.erb. Can someone explain me this error ? The only thing I have different from that app code is I am running Ruby 2.2.2 instead of 2.3.1 but I don't think that is the reason of the error.

Accessing password reset token Rails 4 and Devise

Posted: 23 Dec 2016 02:17 AM PST

I am trying to test the reset password feature (Devise) within my app using Cucumber. After creating a user i click the reset password link and enter the email address, within my console then I notice the reset_password_token field gets updated

I, [2016-12-23T09:35:49.937441 #2164]  INFO -- :   Parameters: {"utf8"=>"✓", "user"=>{"email"=>"emailaddress@gmail.com"}, "commit"=>"Send me reset password instructions"}  D, [2016-12-23T09:35:49.939803 #2164] DEBUG -- :   User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."email" = $1  ORDER BY "users"."id" ASC LIMIT  1  [["email", "emailaddress@gmail.com"]]  D, [2016-12-23T09:35:50.122728 #2164] DEBUG -- :   User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."reset_password_token" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["reset_password_token", "6e67df7cd7824cf21939a45e9cfe4a399e78216d471432b8b55d7a8cbddc800a"]]  D, [2016-12-23T09:35:50.123615 #2164] DEBUG -- :    (0.1ms)  BEGIN  D, [2016-12-23T09:35:50.125628 #2164] DEBUG -- :   SQL (0.5ms)  UPDATE "users" SET "reset_password_token" = $1, "reset_password_sent_at" = $2, "updated_at" = $3 WHERE "users"."id" = $4  [["reset_password_token", "6e67df7cd7824cf21939a45e9cfe4a399e78216d471432b8b55d7a8cbddc800a"], ["reset_password_sent_at", "2016-12-23 09:35:50.123253"], ["updated_at", "2016-12-23 09:35:50.123915"], ["id", 1]]  

As part of my steps i then get that token and try to use it.

Given(/^the user resets their password$/) do    @user = User.last    visit edit_user_password_path(reset_password_token: @user.reset_password_token)    fill_in 'user_password', with: 'NewPassword'    fill_in 'user_password_confirmation', with: 'NewPassword'    submit_form  end  

Within the reset password email though i notice

<a href="http://localhost:4000/users/password/edit?reset_password_token=ZUjy2Y3snR3u7diRoAC4">Change my password</a>  

Which is generated by

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>  

How do i access the correct token values so i can test the reset of a users password

Thanks

ElasticSearch-Rails multi_match fields

Posted: 23 Dec 2016 01:43 AM PST

lMy model associations:

class CertificatePeriod < ActiveRecord::Base    has_many :certificate_orders    has_many :order_transactions, through: :certificate_orders  end    class CertificateOrder < ActiveRecord::Base    belongs_to :user    belongs_to :certificate_period    has_one :order_transaction  end    class OrderTransaction < ActiveRecord::Base    belongs_to :certificate_order  end  

In OrderTransaction model:

class OrderTransaction < ActiveRecord::Base    def as_indexed_json(options={})      self.as_json(only: [:id, cardholdername, :userid],      include: {certificate_order: {include: {user: {only: [:first_name, :last_name], methods: :full_name}}}})    end  end  

Example response of this indexed:

{"id"=>7235,   "cardholdername"=>"NUR SARUHAN",   "userid"=>"zzzyyyxxxx",   "certificate_order"=>    {"id"=>292,     "user_id"=>13186,     "certificate_enrollment_id"=>768,     "slug"=>"eafe0be5-0b1f-4e4f-8929-d3f9330a4a86f7c25b1199dcd5",     "created_at"=>Mon, 11 Apr 2016 18:30:58 EEST +03:00,     "updated_at"=>Mon, 11 Apr 2016 18:30:58 EEST +03:00,     "user"=>{"first_name"=>"Nur", "last_name"=>"SARUHAN", "full_name"=>"NUR SARUHAN"}}}  

I have used search query something like this:

query: {    bool: {      must: [        {ids: {values: @certificate_period.order_transactions.pluck(:id)}},        {bool: {          should: [            {multi_match: {query: params[:q], fields: ['cardholdername', 'certificate_order.user.first_name']}}          ]        }}      ]    }  }).records.to_a  

My question is:

Actually this search query has worked but the following lines are returned exactly same records.

{multi_match: {query: params[:q], fields: ['cardholdername', 'certificate_order.user.first_name']}}  

and

{multi_match: {query: params[:q], fields: ['cardholdername']}}  

It is returned an empty array if I just use certificate_order.user.first_name as parameter in multi_match fields. So there is no effect of certificate_order.user.first_name. I have googled for 3 days but I haven't found right answer. What should I do to get the value of the certificate_order.user.first_name parameter?

Is it possible to run a Rails 4.2 app on Ruby 2.4?

Posted: 23 Dec 2016 03:31 AM PST

I want to try out a Rails 4.2 app on Ruby 2.4.

However, when I try doing it, I get errors about the json gem version 1.8.3 failing to install.

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.        current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator  /Users/agrimm/.rbenv/versions/2.4.0-rc1/bin/ruby -r ./siteconf20161223-91367-cql0ne.rb extconf.rb  creating Makefile    current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator  make "DESTDIR=" clean    current directory: /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3/ext/json/ext/generator  make "DESTDIR="  compiling generator.c  generator.c:861:25: error: use of undeclared identifier 'rb_cFixnum'      } else if (klass == rb_cFixnum) {                          ^  generator.c:863:25: error: use of undeclared identifier 'rb_cBignum'      } else if (klass == rb_cBignum) {                          ^  2 errors generated.  make: *** [generator.o] Error 1    make failed, exit code 2    Gem files will remain installed in /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/gems/json-1.8.3 for inspection.  Results logged to /Users/agrimm/.rbenv/versions/2.4.0-rc1/lib/ruby/gems/2.4.0/extensions/x86_64-darwin-14/2.4.0-static/json-1.8.3/gem_make.out    An error occurred while installing json (1.8.3), and Bundler cannot continue.  Make sure that `gem install json -v '1.8.3'` succeeds before bundling.  

which I assume is due to the unification of Fixnum and Bignum into Integer.

If I add to the Gemfile a constraint that json has to be version 2.0.0, then it complains that Rails 4.2 requires json ~> 1.7, which forbids 2.0.0.

Am I out of luck unless the maintainers of Rails decide to make a change to a non-5.x version of Rails, or the maintainers of the json gem decide to make a new non-2.x version of their gem?

How to post data from one rails app to another in rails?

Posted: 23 Dec 2016 04:21 AM PST

I have to post data from one rails app to another and get a response in return from the latter app to the former.Both are RESTFUL apps

my api to post data from the former app is as follows

 class OrderApiController < ApiController      def send_invoice_data          response = Hash.new          result = Hash.new          order = Order.includes(:status, :user, payment:                    [:status]).where(txnid: params[:txnid]).first          if order              if (['Notary', 'Attestation','Franking'].include?                 order.service.name)                  no_of_copies = ((order.answers.where(question_id:                  [37,15]).length > 0) ? order.answers.where(question_id:                   [37,15]).first.body : 0).to_i               else                  no_of_copies = ((order.answers.where(question_id:                   [37,15]).length > 0) ? order.answers.where(question_id:                       [37,15]).first.body : 0).to_i + 1              end              result['order'] = {                        id: order.id,                         txnid: order.txnid,                         service_name: order.service.name,                         :                        :                        discount: order.discount || '',                        stamp_amount: order.stamp_amount || '',                        delivery_amount: order.delivery_amount || '',                        no_of_copies: no_of_copies                        }               response.merge! ApiStatusList::OK              response['result'] = result          else              response.merge! ApiStatusList::INVALID_REQUEST          end          render :json => response      end     end  

The controller code for the latter app is as follows:

  class InvoiceApiController < ApiController            def order_invoice              response = Hash.new              result = Hash.new              debugger              if params[:order] && params[:order][:txnid]                   @order = params[:order]                  @order['stamp_amount'] = params[:order][:stamp_amount] || ''                  @order['txnid'] = params[:order][:txnid]                  @order['service_name'] = params[:order][:service_name] || ''                  @order['payment_date'] = params[:order][:payment_date]                  :                  :                  @order['discount'] =  params[:order][:discount] || ''                  @no_of_copies = params[:order][:no_of_copies]                  pdf = WickedPdf.new.pdf_from_string(                  render_to_string(template:                   'invoices/generate_invoice.pdf.erb', filename: params[:order]                   [:txnid] + ".pdf" ,                                  type: 'application/pdf', disposition:                   'attachment', print_media_type: true))                  save_path = Rails.root.join('pdfs', @order['txnid'] + ".pdf")                  File.open(save_path, 'wb') do |file|                    file << pdf                    filename = @order['txnid'] + ".pdf"                  end                 file_name =  @order['txnid'] + ".pdf"                 upload = Invoice.upload(save_path, file_name)                 response['result'] = upload                 response.merge! ApiStatusList::OK              else                  response.merge! ApiStatusList::INVALID_REQUEST              end               render :json => response             end  

The second app sends the link of the pdf generated invoice as response back to the former app.

The link for the later app would like this:

http://192.168.0.104:3000/api/v0/generate_invoice?key=value

How do I achive this. I am a rails novice quite new to RESTFUL api development as well.So please help with elaboration for the solution.

How to add images to a word (docx) template in rails?

Posted: 23 Dec 2016 01:37 AM PST

I have a docx template with header and footer and some text in it. Now I want to add some images with a specified max size to the document.

If I try and do it with pandoc-ruby gem and generate a html string and convert it to a word document, then I don't get an option to add header and footer to the generated doc using pandoc.

create button for link_to in html erb for email

Posted: 23 Dec 2016 04:41 AM PST

I am generating an email from a html.erb file in my rails application for the user to confirm their email address. I am trying to make the link_to line below a green button just like I use in other emails. However it shows up as a plain text link.

This is the link I am having trouble with

      <tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">        <td class="content-block" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;" valign="top">            <%= link_to 'Confirm Email', confirmation_url(@resource, confirmation_token: @token), class: 'btn-sm-mpgreen' %>        </td>        </tr>  

And it looks like this in the email

enter image description here

This is the green button from another email I create that I want to use above also.

                    <a href="<%= ENV['EXTERNAL_URL'] %>/#/new_match" class="btn-primary" itemprop="url" style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2em; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; text-transform: capitalize; background-color: #13904B; margin: 10px 0; border-color: #13904B; border-style: solid; border-width: 10px 20px;">Schedule Match</a>  

Which looks like this in the email

enter image description here

sharetribe engine as a gem within Core app, loading error with gem's Rails::Application

Posted: 23 Dec 2016 01:20 AM PST

I'm attempting to turn sharetribe into a gem via mountable engine to extend it's functionality and add features without touching it's codebase as much as possible.

https://github.com/sharetribe/sharetribe

I've run through the process of creating the engine and applying sharetribe, and am running into

sharetribe_engine/config/environments/common.rb:3:in `': uninitialized constant Kassi (NameError)

Kassi is defined within /config and I can't determine where to specify to load it (just within test/dummy for now), if that is actually the problem.

https://github.com/kylegraydev/sharetribe-gem

How do I sort on an association of a specific user?

Posted: 23 Dec 2016 01:33 AM PST

I have a Profile that can be published. A profile belongs_to :user and has_many :ratings.

A User has_one :profile, and has_many :ratings.

A Rating belongs_to :profile && belongs_to :user.

These are the schemas for the above models:

Profile.rb:

# == Schema Information  #  # Table name: profiles  #  #  id                      :integer          not null, primary key  #  first_name              :string  #  last_name               :string  #  created_at              :datetime         not null  #  updated_at              :datetime         not null  #  user_id                 :integer  

User.rb:

# == Schema Information  #  # Table name: users  #  #  id                     :integer          not null, primary key  #  email                  :string           default(""), not null  #  created_at             :datetime         not null  #  updated_at             :datetime         not null  #  first_name             :string  #  last_name              :string  

Rating.rb

# == Schema Information  #  # Table name: ratings  #  #  id         :integer          not null, primary key  #  speed      :integer          default(0)  #  passing    :integer          default(0)  #  tackling   :integer          default(0)  #  dribbling  :integer          default(0)  #  profile_id :integer  #  user_id    :integer  #  created_at :datetime         not null  #  updated_at :datetime         not null  #  

What I want to do is to find all the profiles, ranked by 1 rating attribute....e.g. all published profiles ranked by passing (highest to lowest).

I tried something like this:

Profile.published.where(id: coach.ratings.order(passing: :desc).pluck(:profile_id))  

But that doesn't always give me the profiles in the order I expect.

So how do I do this query that allows me to get these profiles ranked by all of those ratings accordingly?

Edit 1

Please Note The key thing here is that I need to find the ratings on a profile left by a specific user.

In my query above, coach = User.find(7).

So each User leaves a bunch of ratings on many profiles.

What I want to do is filter all the profiles, that have a specific rating (say speed) and order those profiles, by the speed rating from highest to lowest (but this is user specific).

How to implement a shared form for edit and new for RoR application

Posted: 23 Dec 2016 12:29 AM PST

There are two models whose relationship is one to many. I would like to implement a shared form for new and edit action.

Here are example.

# Migration  class CreateFoo < ActiveRecord::Migration    def change      create_table :Foo do |t|        t.string :name        ...      end    end  end    class CreateBar < ActiveRecord::Migration    def change      create_table :Bar do |t|        t.string :name        t.integer :foo_id    end  end    # Model  class Foo < ActiveRecord::Base    has_many :bars  end    class Bar < ActiveRecord::Base    belongs_to :foo  end    # part of shared form      <%form_for @foo do |f|%>    <%= f.label :name %>:    <%= f.text_field :name %>      # text field for name1 of Bar    # text field for name2 of Bar    # text field for name3 of Bar      ...    <%end%>  

When 'new' Foo, the form supports to input multiple names of Bar; when editing Foo, the form supports to edit the existing name of Bar related to some Foo.

I really appreciate that corresponding controller can be given.

Thanks.

No comments:

Post a Comment