Wednesday, May 4, 2016

Ruby on Rails, getting attributes from multiple model instances | Fixed issues

Ruby on Rails, getting attributes from multiple model instances | Fixed issues


Ruby on Rails, getting attributes from multiple model instances

Posted: 04 May 2016 06:57 AM PDT

In my Ruby on Rails project, I have a Country model class and a Proposal model class. A country has many proposals and a proposal belongs to a specific country. Each proposal consists of 30 questions. I want to display each question for every proposal for that specific country.

My initial idea for syntax was:

<% @country.proposal.each do |proposal| %>    <% end %>  

However, this resulted in an error message "undefined method `proposal' for #Country:0x007f67b51cf178"

Any ideas?

counter_cache in Rails on a scoped association

Posted: 04 May 2016 06:52 AM PDT

I have User model which has_many :notifications. Notification has a boolean column seen and a scope called :unseen which returns all notifications where seen is false.

class User < ApplicationRecord    has_many :notifications    has_many :unseen_notifications, -> { unseen }, class_name: "Notification"  end  

I know that I can cache the number of notifications if I add a column called notifications_count to users and add counter_cache: true to my belongs_to call in Notification.

But what if I want to cache the number of unseen notifications a user has? I.e. cache unseen_notifications.size instead of notifications.size? Is there a built-in way to do this with counter_cache or do I have to roll my own solution?

Rails left join conditional

Posted: 04 May 2016 06:47 AM PDT

I don't know good way to write activerecord query to select necessary data. I have Customer table, that has many items

Customers(id)  

Item table, that belongs to customer(One customer can have an item, then this item can belong to another customer, so customer_id is the current customer)

Items(id, price, customer_id)  

Line item (join table: items many-to-many orders)

LineItems(id, item_id, order_id, price, quantity)  

Order has_many items through line_items.

Orders(id, total, status, customer_id)  

Well, I want to get all items, that is not included to orders which do not have status 1, 2, 3(status is an integer field)

So I need join customer and items, then left join with orders with conditional(status is not included ...) through line_items table. How can I implement it via ActiveRecord. Or SQl. By the way: I use psql. Thanks.

Question is Well, I want to get all items, that is not included to orders which do not have status 1, 2, 3(status is an integer field)

'devise' gem - permission denied @rb_sysopen

Posted: 04 May 2016 06:34 AM PDT

I have installed 'devise' gem.

When I tried to run

rails g devise User  

I get the following error.

/home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:101:in `initialize': Permission denied @ rb_sysopen - /home/cbls-2/academics/assistant/config/routes.rb (Errno::EACCES)  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:101:in `open'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:101:in `replace!'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:59:in `invoke!'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:94:in `action'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb:30:in `insert_into_file'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/generators/actions.rb:224:in `block in route'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:194:in `block in in_root'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:184:in `block in inside'  from /home/cbls-2/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/fileutils.rb:128:in `chdir'  from /home/cbls-2/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/fileutils.rb:128:in `cd'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:184:in `inside'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/thor-0.19.1/lib/thor/actions.rb:194:in `in_root'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/generators/actions.rb:223:in `route'  from /home/cbls-2/.rvm/gems/ruby-2.3.0/gems/devise-4.1.0/lib/generators/devise/devise_generator.rb:22:in `add_devise_routes'  

I have Rails 4.2.6, Ruby 2.3.0

This is my gemfile

 gem 'rails', '4.2.6'   gem 'mysql2'   gem 'devise'   gem 'sass-rails', '~> 5.0'   gem 'uglifier', '>= 1.3.0'   gem 'coffee-rails', '~> 4.1.0'   gem 'therubyracer', platforms: :ruby    gem 'jquery-rails'    gem 'turbolinks'  gem 'jbuilder', '~> 2.0'  gem 'sdoc', '~> 0.4.0', group: :doc     gem 'bcrypt', '~> 3.1.7'   gem 'unicorn'   gem 'capistrano-rails', group: :development    group :development, :test do        debugger console     gem 'byebug'  end    group :development do    gem 'web-console', '~> 2.0'    gem 'spring'  end  

Could not run 'rails g activeadmin:resource User' also. It throws the same error.

How do I extract transaction details from a redirected Payment Processor Site and save to my rails 4 db

Posted: 04 May 2016 06:26 AM PDT

Am working on a Paid Ads Job Board. I have implemented a Nigerian Payment Processor (VoguePay) which provided no documentation on using its API on Ruby on Rails Framework to get details from transactions and do anything with it.

Note

VouguePay Payment Processor has a POST method with action redirecting to it payment website (https://voguepay.com/pay/) in order to be able to make transaction.

This is what I have done such that the process is done inside my App

I enclosed VoguePay API in an iFrame html tag such that the process is done on my app and not go outside my app to make payment.

Below are my codes

JobsController

class JobsController < ApplicationController    layout false, only: [:voguepay]      def index      @jobs = Job.paid_ad    end      def show      @job = Job.find(params[:id])    end      def edit      @job = Job.find(params[:id])      redirect_to @job if @job.paid?    end      def update      @job = Job.find(params[:id])      if !(@job.paid?)        @job.update_attributes(stripeEmail: params[:stripeEmail], payola_sale_guid: params[:transaction_id])        # The "has_key?" Returns true if the given key/attribute is present in hash e.g.        # h = { "a" => 100, "b" => 200 }        # h.has_key?("a")   #=> true        # h.has_key?("z")   #=> false.        # So this means --Update job_params if the given key/attribute is present or not in job.        @job.update(job_params) if params.has_key?(:job)        redirect_to  preview_job_path(@job) #show_job_path      else        render :edit      end    end      def new      @job = Job.new    end      def create      @job = Job.new(job_params)      if @job.save        redirect_to preview_job_path(@job)      else        render :new      end    end      def preview      @job = Job.find(params[:id])      redirect_to @job if @job.paid?    end      def payment      @job = Job.find_by_permalink(params[:permalink])      redirect_to job_path(@job) if @job.paid?    end      def search      @jobs = Job.search(params)    end        def voguepay      #Nothing here yet.    end      private      def job_params      params.require(:job).permit(:title, :category, :location, :description, :to_apply, :email, :company_name, :website)    end  end  

jobs\payments.html.erb

<iframe id="vogueFrame" seamless="seamless" target="_self" src="<%= '/../jobs/shared/voguepay' %>"          style="width: 100%; height: 1200px; align:center"          scrolling="no"          marginwidth="0"          marginheight="0"          frameborder="0"          vspace="0"          hspace="0">  </iframe>  

VoguePayForm which was rendered inside iframe src above

<%= render 'shared/layout_for_voguepay'%>  <%= render 'shared/four_breaks' %>  <div class="container">    <div class="row col-md-12">      <p class="text-center"><strong style="font-weight: bold; font-size:20px;">STEP 3 (OF 3): ENTER YOUR CARD EMAIL & PROCEED TO MAKE PAYMENT</strong></p>    </div>  </div>  <%= render 'shared/two_breaks' %>  <div class="container">    <div class="row">      <div class='col-md-4'></div>      <div class="col-md-4 panel panel-default">        <%#= render 'shared/two_breaks' %>          <form method="POST" action="https://voguepay.com/pay/">          <input type="hidden" name="v_merchant_id" value="demo" />          <input type="hidden" name="memo" value="Payment for Far-Flung Jobs" />          <input type="hidden" name="success_url" value="http://localhost:3000" />          <input type="hidden" name="cur" value="NGN" />          <input type="hidden" name="item_1" value="Job Ads" />          <input type="hidden" name="price_1" value="3000" />          <input type="hidden" name="description_1" value="FarFlung Jobs Ads Payment" /><br />                  <div class='form-row'>              <div class="col-md-12 form-group">                <button name="submit"  type="submit" class="btn" style="color: #ffffff; background: #990099 none; border-bottom: double; margin-bottom: 13px;" id="submit" >MAKE PAYMENT</button>              </div>            </div>        </form>      </div>    </div>  </div>  

VoguePay Payment Network Log

Browser Network Log

My Question/Desire/What I like to do

How do I extract transaction details from that redirected Payment Processor Site and save details of my choice to my Rails 4 database/table using JavaScript or JSON?

Any help will be appreciated. Thanks.

Select with ability to create new

Posted: 04 May 2016 06:41 AM PDT

I'm searching the right solution for such functionality:

  1. We have model Book that has belongs to Author
  2. When creating new book we can select an author from existing.
  3. Under the select input there is a link 'Create new author'.
  4. On clicking this link modal window appears with form for author (:name, :biography, :picture etc.).
  5. After submitting the form the author is created and available for selection.

Don't want someone to write ready code for me, but I would be very grateful if someone tells me the right way to solve this issue

Ruby On Rails Application with angularJS about AJAX

Posted: 04 May 2016 06:38 AM PDT

I'm new to angularJS and Rails,and I tried to building a Rails application with AngularJS

and now, I want to do a POST request to sent data insert database

Activity Controller

def create          @activity = Activity.new(params[:activity])            respond_to do |format|              if @activity.save                  format.html {redirect_to activities_url}                  format.json { render activities_url, status: :created, location: @activity}              end          end    end  

Activity Coffee JS

app = module('activity', ['ngAnimate'])  app.controller 'FormCtrl', ($scope, $http) ->      config = {          header: {              'Content-Type': 'application/json'          }      }      @test = ->          $http.post('/activities.json', {title: 'test1'}, config).success (data, status) ->              console.log(data)              console.log(status)  return  

Console log

Started POST "/activities.json" for ::1 at 2016-05-04 21:06:10 +0800  Processing by ActivitiesController#create as JSON    Parameters: {"title"=>"test1", "activity"=>{"title"=>"test1"}}  Can't verify CSRF token authenticity  Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)  

I created a button of ng-click to trigger test function but I got information like console log, How can I do to fix it?

Generate a json for chart in Jbuilder with Ruby on Rails

Posted: 04 May 2016 06:03 AM PDT

I´m trying create a file for a FLOT chart with next data:

{          'label': 'Clicks',          'color': Colors.byName('purple-300'),          data: [          ['1', 40],          ['2', 50],          ['12', 135]]  }  

How can I create the data section array in jBuilder?

Thanks!!!

How to 'back calculate' Merit points?

Posted: 04 May 2016 05:54 AM PDT

I'm trying to add a reputation system into an existing app using Merit.

I want to back calculate points for all users based on their historical activity. Merit has quite a complicated internal structure with several tables, and I think I may be missing some important steps. Below is what I have so far, and I'm grateful for pointers from anyone more familiar with this gem.

To keep things simple, let's say I want to

score 2, to: :user, on: 'comments#create'  

and that I have a Comment table full of records that look something like this

Comment id: 56, content: "My comment", user_id: 247, commentable_id: 2, commentable_type: 'Object', created_at: "2016-04-04 08:56:17", updated_at: "2016-04-04 17:03:55">  

My current approach looks like this

Comment.all.each do |c|    score_point = Merit::Score::Point.create( num_point: 2, log: nil, created_at: c.created_at)    action = Merit::Action.create(user_id: c.user_id, action_method: 'create', action_value: nil, had_errors: false, target_model: c.class.name, target_id: c.id, processed: true, created_at: c.created_at)    activity_log = Merit::ActivityLog.create( action_id: action.id, related_change_type: "Merit::Score::Point", related_change_id: score_point.id, description: "", created_at: c.created_at)   end  

There is also a Merit::Score and Merit::Sash table, but I'm not clear on what these do and whether these records also need to be created.

Is there anything else that I have overlooked?

As an aside, what is the purpose of Merit::Action.action_value, Merit::ActivityLog.description and Merit::Score::Point.log, or are these simply free text strings?

Migrating from passenger to puma, random "KeyError"

Posted: 04 May 2016 05:45 AM PDT

I'm trying to migrate my heroku hosted application from passenger to puma (for multithreading).

But i'm facing random (1/1000) KeyError (key not found: "...") error, from various place in my code :

  • @user = User.find(params[:id]) : KeyError (key not found: "\x86")
  • self.where(hosts: host).first : KeyError (key not found: ".")
  • _client = current_user.clientroles.first.client : ActionView::Template::Error (key not found: "\xB8"):

These errors appear when i load my application with concurrent requests, whatever thread count (even with 1 thread).

Best regards

Outputing position in an array

Posted: 04 May 2016 06:05 AM PDT

This is probably a really simple question! If I have an array like the following:

[Red, Blue, Pick, Orange]  

The array has been sorted and I'd to show what position they are inside the array.

E.g.

  1. Red
  2. Blue
  3. Pink
  4. Orange

I'd display the colours to the user like this but cannot work out how to display showing that red is number 1, blue is number 2 and 3 is pink in my sorted list.

<% @colours.each do |colour| %>   <%= colour %>  <% end %>  

Elasticsearch with Rails - mapping `_all` field in 2.2 version

Posted: 04 May 2016 05:18 AM PDT

I got a multi model search and my configuration looks like:

settings analysis: {    ...  } do    mappings do      indexes "_all",        type: "string",        analyzer: "ngram_analyzer",        search_analyzer: "whitespace_analyzer"    end  end  

It all worked great on Elasticsearch 2.1 but breaks on 2.2 with:

Elasticsearch::Transport::Transport::Errors::BadRequest: [400]  {    "error": {      "root_cause": [        {          "type": "mapper_parsing_exception",          "reason": "Failed to parse mapping [insurer]: Field [_all] is defined twice in [insurer]"        }      ],      "type": "mapper_parsing_exception",      "reason": "Failed to parse mapping [insurer]: Field [_all] is defined twice in [insurer]",      "caused_by": {        "type": "illegal_argument_exception",        "reason": "Field [_all] is defined twice in [insurer]"      }    },    "status": 400  }  

How can fix it to index all fields in 2.2?

AWS Ruby SDK V2: Aws error command not found

Posted: 04 May 2016 05:14 AM PDT

I am using cloud9 with ruby on rails, I have just installed the AWS-SDK and was following the amazon documents to set it up (Listed below).

http://docs.aws.amazon.com/sdk-for-ruby/latest/DeveloperGuide/aws-ruby-sdk-getting-started.html#aws-ruby-sdk-credentials-client

But on the second step which is just to run Aws.config I am getting a Aws command not found error.

I tried with capital letter ect but it is not recognizing AWS.

I was thinking it may possibly be the directory I am in but there is nothing saying I should be in anything but the root directory for my applications. None of he other gems have this problem byt since I am using cloud9 I thought I would check. I have included the director for the gem below if you think this may be the issue:

/usr/local/rvm/gems/ruby-2.3.0/gems/aws-sdk-2.3.1  

This is the output from my console with the top line showing aws-sdk-core 2.3.1 is installed and the errors at the bottom when I try to enter aws into the console.

Using aws-sdk-core 2.3.1      Using rails-deprecated_sanitizer 1.0.3      Using globalid 0.3.6      Using activemodel 4.2.5      Using jbuilder 2.4.1      Using rails-html-sanitizer 1.0.3      Using aws-sdk-resources 2.3.1      Using rails-dom-testing 1.0.7      Using activejob 4.2.5      Using activerecord 4.2.5      Using aws-sdk 2.3.1      Using actionview 4.2.5      Using actionpack 4.2.5      Using actionmailer 4.2.5      Using railties 4.2.5      Using sprockets-rails 3.0.4      Installing aws-sdk-rails 1.0.1      Using coffee-rails 4.1.1      Using jquery-rails 4.1.1      Using rails 4.2.5      Using sass-rails 5.0.4      Using web-console 2.3.0      Using turbolinks 2.5.3      Bundle complete! 15 Gemfile dependencies, 65 gems now installed.      Use `bundle show [gemname]` to see where a bundled gem is installed.      discoveredfm:~/workspace $ aws      bash: aws: command not found      discoveredfm:~/workspace $ Aws      bash: Aws: command not found      discoveredfm:~/workspace $ AWS      bash: AWS: command not found      discoveredfm:~/workspace $ bundle show aws-sdk      /usr/local/rvm/gems/ruby-2.3.0/gems/aws-sdk-2.3.1      discoveredfm:~/workspace $   

Thanks for your help.

How do I redirect_to with Authorization headers in rails

Posted: 04 May 2016 06:34 AM PDT

Trying to pass Oauth access token via headers to another url (May or may not be another domain).

haml code-

%a{:href => "/external_redirect?user_id=#{@user['id']}", :id => 'external_url' }  

controller -

def external_redirect     external_url = "http://external.abc.com:3008/consumerlogin?user_id=#{params["user_id"]}"     response.headers["Authorization"] = "OAuth #{cookies[ :access_token ]}"     redirect_to external_url    end   

Am I doing this right? The header is not being sent to the external_url.

ActiveRecord::MultiparameterAssignmentErrors when a parameter was left blank in date_select

Posted: 04 May 2016 04:36 AM PDT

I'm having trouble validating date fields using date_select helper from form_builder, whenever one of the parameters is left blank (e.g year params). I'm using the validates_timeliness gem and it works perfectly with datetime_select however it doesn't work on date_select.

on my model class I do have this validation:

validates_date :start_date, on_or_before: :today, allow_blank: true  

this is the field on the view (uses simple_form)

= f.input :start_date  

and this are the parameters (start_date(1i) is for year params and was left blank):

"start_date(1i)"=>"",  "start_date(2i)"=>"2",  "start_date(3i)"=>"3"  

and this is what I got after submitting it

1 error(s) on assignment of multiparameter attributes [error on assignment [nil, 2, 3] to start_date (undefined method `<' for nil:NilClass)]  

Hope somebody can help me out with this. Thank you in advance.

Rspec delete object failure with method has_many throw, No route matches {:action=>"destroy"

Posted: 04 May 2016 05:08 AM PDT

Need some help to make rspec test to pass, my goal is to delete a relationship that has been created with the method has_many throw. I followed this MHartl's tutorial.

relationships_controller.rb :

class RelationshipsController < InheritedResources::Base          def create          user = User.find(params[:followed_id])          current_user.follow(user)          redirect_to user        end          def destroy          user = Relationship.find(params[:id]).followed          current_user.unfollow(user)          redirect_to user        end      end  

relationships_controller_spec.rb :

require 'rails_helper'    describe RelationshipsController do    let(:relationship) { create(:relationship) }    let(:user) { create(:user) }      before do      sign_in :user, create(:user)    end      describe '#create' do      let!(:followed) { create(:user) }      it "should require logged-in user to create relationship" do        expect{          post :create, followed_id: followed.id        }.to change(Relationship, :count).by(1)        redirect_to root_path      end    end      describe '#destroy' do      let!(:relationship) { create(:relationship) }        it "should require logged-in user to destroy relationship" do        expect {          delete :destroy, id: relationship.id        }.to change(Relationship, :count).by(-1)        redirect_to root_path      end    end  end  

routes.rb :

Rails.application.routes.draw do    devise_for :users, controllers: { sessions: "users/sessions" }    devise_for :admin_users, ActiveAdmin::Devise.config      ActiveAdmin.routes(self)      mount Peek::Railtie => '/peek'      resources :users do      member do        get :following, :followers      end    end    resources :relationships, only: [:create, :destroy]      root to: "records#index"  end  

user.rb:

class User < ActiveRecord::Base    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable,           :validatable, :confirmable, :timeoutable      # Associations    has_many :active_relationships, class_name:  "Relationship",                                    foreign_key: "follower_id",                                    dependent:   :destroy    has_many :passive_relationships, class_name:  "Relationship",                                    foreign_key: "followed_id",                                    dependent:   :destroy    has_many :following, through: :active_relationships, source: :followed    has_many :followers, through: :passive_relationships, source: :follower      # Follows a user.    def follow(other_user)      active_relationships.create(followed_id: other_user.id)    end      # Unfollows a user.    def unfollow(other_user)      active_relationships.find_by(followed_id: other_user.id).destroy    end      # Returns true if the current user is following the other user.    def following?(other_user)      following.include?(other_user)    end  end  

Factory:

FactoryGirl.define do    factory :relationship do      follower_id 1      followed_id 1    end  end  

Failures:

1) Relationships GET /relationships works! (now write some real specs)       Failure/Error: get relationships_path         ActionController::RoutingError:         No route matches [GET] "/relationships"      2) RelationshipsController#destroy should require logged-in user to destroy relationship       Failure/Error: active_relationships.find_by(followed_id: other_user.id).destroy         NoMethodError:         undefined method `id' for nil:NilClass  

Rails delete something from databse but references fails

Posted: 04 May 2016 05:52 AM PDT

I want to delete something from my database. The value references some other tables.

Error is:

Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails  

How can I resolve this properly?

If I add some constraints like on delete cascade the other values won't be deleted right?

Edit:

def delete     @vid = Movie.find params[:id]     @vid.delete     redirect_to :action => :add  end  

Ruby on Rails - Optional user message when they submit their vote to database

Posted: 04 May 2016 03:51 AM PDT

My app allows users to see a list of questions and allows them to vote for an option (uniquely). I have a users table, a questions table, an options table and an answers table.

I've created the migration to add the column message to the answers table and I can show the messages on the page, just need to actually send the message to the DB table - this is the button to allow the user to vote:

<%= link_to 'Vote', question_option_upvote_path(@question, option), data: { confirm: 'Are you sure you want to vote for this option?' }, :class => 'voteNow', method: :post %>  

I'm struggling to hook up the textarea to be sent when the user clicks to vote, I'm using simply <%= text_area :message, autofocus: true %> to create my textarea on it's own. Do I need to setup a whole form for this or is there a simple way to pull the contents when the user votes? My options controller is:

class OptionsController < ApplicationController        def create          @question = Question.find(params[:question_id])          @option = @question.options.create(option_param)          redirect_to question_path(@question)      end        def upvote          @question = Question.find(params[:question_id])          @option = Option.find(params[:option_id])          Answer.create(user_id: current_user.id, question_id: @question.id, option_id: @option.id)          redirect_to question_path(@question)      end        private        def option_param          params.require(:option).permit(:option_text)      end  end  

Let me know if I need to include anything else in this message!

Devise not including engine namespace in unauthorized route redirection

Posted: 04 May 2016 03:51 AM PDT

So I found a solution to this, but I'd like to find out if it's my setup that is wrong or if it's a Devise issue because my solution involves modifying Devise's code.

I have a Rails engine named ScribeEngine.

The problem is that when I try to access a protected controller (before_filter authenticate_admin!), if the user isn't logged in I am redirected to /admins/sign_in instead of /scribe_engine/admins/sign_in, resulting in a routing error.

In my config/initializers/devise.rb is the following configuration :

config.router_name = :scribe_engine  config.parent_controller = 'ScribeEngine::ApplicationController'  

In my config/routes.rb :

ScribeEngine::Engine.routes.draw do       root to: "pages#index"       resources :pages     resources :sections, except: [:show, :index]       devise_for :admins, class_name: "ScribeEngine::Admin", module: :devise     ScribeEngine::Page.set_root     ScribeEngine::Page.draw_routes    end  

In my lib/scribe_engine/engine.rb:

module ScribeEngine    class Engine < ::Rails::Engine      isolate_namespace ScribeEngine    end  end  

For some reason I've been unable to use the solution provided here Devise in a mounted engine uses wrong url for a 401

I can't get the custom failure app to load, always getting an uninitialized constant CustomFailure (NameError)

Therefore I decided to get to the bottom of this by checking the failure_app in the devise gem devise/lib/devise/failure_app.rb

The interesting part is the scope_url function.

There I started adding opts[:subdomain] = "scribe_engine" directly to check if that would solve it, as stated in the previously linked solution.

This did not work as I ended up getting scribe_engine.localhost:3000 instead.

After fiddling around with the code, I managed to get the right url by modifying the end of the function from :

  if context.respond_to?(route)      context.send(route, opts)    elsif respond_to?(:root_url)      root_url(opts)    else      "/"    end  

to :

  if context.respond_to?(route)      context.url_for(controller: "devise/sessions", action: "new")    elsif respond_to?(:root_url)      root_url(opts)    else      "/"    end  

This worked, but I am losing the opts hash in the process which doesn't seem ideal obviously.

So should I file an issue for this, or is it simply my engine setup that is wrong ?

add animate.css classes then remove the element with remove

Posted: 04 May 2016 04:02 AM PDT

I'm trying to add some css classes on my label/checkbox tick, then remove the classes and then remove the item once it's been checked. Though I'm struggling and only managing to do one or the other.

$(function () {      $("label[for='<%= @todo.id %>']").click(function () {          el = $("#todo-container-<%= @todo.id %>");          el.addClass('animated fadeOut');          el.one('webkitAnimationEnd oanimationend msAnimationEnd animationend',          function (e) {              el.removeClass('animated fadeOut');              el.remove();          });      });  });  

Here I'm trying (in my complete.js.erb file) to on the label click (which checks the checkbox) add the animated and fadeOut classes to the container, and then remove the class as well as container element after it has faded.

Can anyone help me out? My code is only doing 1 of my 2 requirements

Empty view paths when using rspec to test a rubygem

Posted: 04 May 2016 03:36 AM PDT

I'm having trouble getting rspec to render a view. The following error keeps getting returned when I run rake spec:

ActionView::MissingTemplate:         Missing template spec/views/current_user with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby]}. Searched in:  

The Searched in: part is what I suspect is going wrong, as it implies there are no view paths whatsoever defined.

Here's how the template is rendered:

render 'spec/views/current_user', :layout => false  

And the dummy rails app is set up in spec_helper.rb with:

require 'rails'  require 'action_controller'  class TestRailsApp < Rails::Application    config.secret_key_base = '1234'    config.eager_load = false if Rails::VERSION::MAJOR == 4      initialize!  end    module ApplicationHelper  end    class ApplicationController < ActionController::Base  end  

If it helps, I'm trying to contribute to the render_anywhere gem, and I've asked in an issue there but not had a reply.

rails rescue_from ScriptError

Posted: 04 May 2016 05:10 AM PDT

According to the family tree of Exception. SyntaxError is child to ScriptError

I wish to handle Syntax and/or ScriptError in my rails application.

Exception      NoMemoryError      ScriptError          LoadError          NotImplementedError          SyntaxError      SignalException          Interrupt      StandardError          ArgumentError          IOError              EOFError          IndexError              StopIteration          LocalJumpError          NameError              NoMethodError          RangeError              FloatDomainError          RegexpError          RuntimeError          SecurityError          SystemCallError          SystemStackError          ThreadError          TypeError          ZeroDivisionError      SystemExit      fatal  

I did:

rescue_from ScriptError, :with => :notify_on_landing_page

but didn't worked.

Error raised on screen : SyntaxError in Bc::Muse::User::ProfileController#show

I have created an explicit syntax error, it should gracefully rescue it and do the things I want to.

elasticsearch: Aggregating by a specific field with possibility to show all the options available in that field

Posted: 04 May 2016 06:10 AM PDT

For my new rails application i am trying to apply elasticsearch + chewy combination of tools instead of solr + sunspot.

For now i have this parent model class (using sequel gem but it is not really means anything for my particular case)

class Product < Sequel::Model    #has :brand_id field among others  end  

and several Product subclasses like

class Notebook < Product    #has :diagonal field among others  end  

Also, i have defined index model according to chewy documentation

class ProductsIndex < Chewy::Index      Product.subclasses.each do |subclass|      define_type subclass do          subclass.columns.each do |col|          field col          agg col do            { terms: { field: col } }          end        end      end    end    end  

and thus i can facet search results with this query

ProductsIndex::Notebook.filter{match_all}.aggs(:brand_id).aggs['brand_id']['buckets']  

and receive this

[{"key"=>"7", "doc_count"=>5}, {"key"=>"1", "doc_count"=>10}, ... ]  

but if i apply any filter instead of match_all like brand_id: 7 (let it be "HP" in my example) i will receive only one facet for this field

{"key"=>"7", "doc_count"=>5}  

but i still need to get all other buckets to show it in "classic" filter manner on frontend

  • Apple (10)
  • HP (5)
  • ...

as i did it using sunspot facet with :exclude option

How can i achieve this? (ideally, using chewy syntax, but elasticsearch query example can be helpful too)

Thank you


UPDATE

i tried to adapt @Andrei Stefan's code to build aggregation like this

subclass.columns.each do |col|      field col        agg "#{col}s".to_sym do        {            global: {},            aggs: {                col => {                    terms: {                        field: col,                        # size: 10 # << why do i need this?                    }                }            }        }      end    end  

and i receive no errors during ES request

ProductsIndex::Notebook.filter{brand_id == '7'}.aggs(:brand_ids).aggs  

and even have all buckets in the scope what i've got earlier using filter{match_all},

Now, if i complement the filter with diagonal value like

filter{(brand_id == '7') & (diagonal == '12')}  

the doc_count for each bucket for facet aggs(:brand_ids).aggs stays like it was for match_all.

But i expect (according to my db content - not all notebooks have 12' diagonal) that diagonal value would decrease doc_count for :brand_ids facet.

So, still need help here!

Thank you, again!

Display Records if Checkbox is selected

Posted: 04 May 2016 04:08 AM PDT

I am creating a simple form that has Some records and a checkbox on it. Now, when i select the checkbox the first two records should hide.

This is my Controller:

def galleryhome     @gallery_photos = GalleryPhoto.where(gallery_id: params[:id])  end  

This is my view:

<div class="checkbox">      <input type="checkbox" name="remember" id="HideRecord">      <label for="remember" class="optional">Hide photos in albums</label>    </div>  </div>  <div class="all-photo"> <!--start-photo-view-->    <%= hidden_field_tag "Value"%>    <% @gallery_photos.each do |gallery_photo| %>    <ul class="photos-view">      <li class="photo-tile">        <div class="inside-img"><%= image_tag gallery_photo.photo.url%></div>        <div class="inside-img-open">          <a  data-target="#viewlarge-Img" data-toggle="modal" href="#" class="fa fa-search" ></a>        </div>        <div class="photo-name"><%= gallery_photo.photo_file_name%></div>      </li>    </ul>    <% end %>  </div>  

Can anyone please help me?

how to write active record for the following query

Posted: 04 May 2016 03:33 AM PDT

TempUserNote.find_by_sql("select user_avg_table.* from            (select temp_user_notes.*, avg(perception_score) as avg from temp_user_notes group by user_id)            as user_avg_table where avg > 1")  

How can I write this query in ActiveRecord query. As i want to take use of active record. find_by_sql method returns array rather than active_records object

Different display of font size in bootstrap cols

Posted: 04 May 2016 03:16 AM PDT

I have a portfolio page. If portfolio image is present, the row should be devided into two parts. If not - portfolio description in one line. There are three such rows on my page. Some of them can be with image and some not. At the large screen all is good, but at the mobile or ipad the font size of div's without image (col-*-12) is much more bigger than in col-*-6.

 <div class="row">    <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 ">     </div>     <div class="col-xs-10 col-sm-10 col-md-10 col-lg-10">             <% if @portfolio.first_picture.present? %>            <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">              <div class="portfolio-description">               <h2 class="row-header"> Project statement</h2>               <h4 class="p-description"><%= @portfolio.project_statement%></h4>              </div>            </div>            <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 portfolio-pic">              <%= image_tag(@portfolio.first_picture, class: 'portfolio-picture') %>            </div>        <% else %>            <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 outer-desc">              <div class="portfolio-description">               <h2 class="row-header"> Project statement</h2>               <h4 class="p-description"><%= @portfolio.project_statement %></h4>              </div>            </div>        <% end %>      </div>  
@media (min-width: 768px) and (max-width: 991px) {    .row-header {       font-size: 1.8em !important;    }    .p-description {       font-size: 1.3em !important;    }  }  

How can I make all this div's to look with the same font size? (They have the same size, but look differently)

How to expire conditional GET cache when locale changes?

Posted: 04 May 2016 04:06 AM PDT

For a JSON API, I am using fresh_when, like so (simplified):

class BalancesController < ApplicationController    def mine      fresh_when(current_user.balance)    end  end  

This works with ETags (If-None-Match) and updated_at (If-Modified-Since) just fine.

However, I want to invalidate the cache for different languages. Simplified:

class BalancesController < ApplicationController    before_action :set_locale    def mine       fresh_when(current_user.balance)    end      private    def set_locale      @locale = locale_from_headers    end  end  

locale_from_headers is a more complex lib, but for this example it is enough to say that a header "Accept-Language: nl" or "Accept-Language: en" will result in @locale being either :nl or :en.

I want to use this in the etag and if-modified since. So that the fresh_when does not return a cached response when requesting a different language. Like so:

  • get /balances/mine, {}, { "Accept-Language" => "en" } #=> response 200 OK
  • get /balances/mine, {}, { "Accept-Language" => "en", "If-None-Match" => previous_response.headers["ETag"] } #=> response 304 not modified
  • get /balances/mine, {}, { "Accept-Language" => "nl", "If-None-Match" => previous_response.headers["ETag"] } #=> response 200 OK
  • get /balances/mine, {}, { "Accept-Language" => "nl", "If-None-Match" => previous_response.headers["ETag"] } #=> response 304 not modified

So, responses are cached and returned as 304 only when the locales match the cached version.

With cache() blocks, using fragment caching in Rails, adding a locale is simple. How to achieve the same with the fresh_when methods?

Replace video tags from HTML string

Posted: 04 May 2016 06:07 AM PDT

The HTML string is:

"<div>\r\n<video controls=\"controls\" height=\"313\" id=\"video201643154436\" poster=\"/uploads/ckeditor/pictures/18/content_56883622_18f242e114.jpg\" width=\"500\"><source src=\"/uploads/ckeditor/attachments/23/newtons_law.mp4\" type=\"video/mp4\" />Your browser doesn&#39;t support video.<br />\r\nPlease download the file: <a href=\"/uploads/ckeditor/attachments/23/newtons_law.mp4\">video/mp4</a></video>\r\n</div>\r\n\r\n<div>test description</div>\r\n\r\n<div>\r\n<div>\r\n<video controls=\"controls\" height=\"300\" id=\"video201644152011\" poster=\"\" width=\"400\"><source src=\"/uploads/ckeditor/attachments/24/test.mp4\" type=\"video/mp4\" />Your browser doesn&#39;t support video.<br />\r\nPlease download the file: <a href=\"/uploads/ckeditor/attachments/24/test.mp4\">video/mp4</a></video>\r\n</div>\r\n\r\n<p>&nbsp;</p>\r\n</div>\r\n"  

I want to replace all video tags including its content and sub tags with [[ Video ]]

The expected output is:

"<div>\r\n[[ Video ]]\r\n</div>\r\n\r\n<div>test description</div>\r\n\r\n<div>\r\n<div>\r\n[[ Video ]]\r\n</div>\r\n\r\n<p>&nbsp;</p>\r\n</div>\r\n"  

I have tried using the regex /<video\s(.*?)<\/video(?=[>])>/, but it's not working properly.

Defining fish shell as default

Posted: 04 May 2016 02:30 AM PDT

After sets fish as default bash by chsh -s "which fish"

/usr/bin/rails or rails outputs:

Rails is not currently installed on this system. To get the latest version, simply type:      $ sudo gem install rails  You can then rerun your "rails" command.  

and more strange behaivor when which rvm it's outputs nothing, whereas bash works fine.

And earlier when I ran fish manualy it's works fine too. What happened and how to fix it? Thank you in advance.

Ruby on Rails Parse Library Issue

Posted: 04 May 2016 01:38 AM PDT

https://github.com/adelevie/parse-ruby-client

PARSE Library for ROR

Ruby 2.0 Rails 4.2.6

My Query to get all followers from a user

@follow = client.query("Follow").tap do |q|        q.eq("user",@user.pointer)        q.include = "_User"      end.get  

Returns me correct data and

@follow.each do |p|   p["following"] #contains users pointer  end  

BUT displaying this returns

=p["following"].objects.first  

ERROR

undefined method `objects' for #<Parse::Pointer:0x007fefa5506aa8>  

Any help regarding this would be highly appreciated! Thanks :)

No comments:

Post a Comment