Saturday, April 30, 2016

How many app may be deploy on my VPS | Fixed issues

How many app may be deploy on my VPS | Fixed issues


How many app may be deploy on my VPS

Posted: 30 Apr 2016 07:03 AM PDT

I have a VPS that have : RAM : 512 MB, CPU : single core, OS : centos , and unicorn server .

And have 50 GB disk space I want to know how many rails app i can deploy on this vps . Or totally what a rule between number of apps and vps's informations ?

Routing Error: No route matches [POST] "/flex_quiz/new"

Posted: 30 Apr 2016 06:37 AM PDT

In my rails app I'm trying to use a form partial to display the same quiz on the new and edit views. I can see the new view page, but when I hit <%= f.submit "Submit Answers" %> I get an error saying No route matches [POST] "/flex_quiz/new".

Here is the form for line in my partial:

<%= form_for @flex_quiz, url: url do |f| %>  

And here's how the locals stand in my new view:

 <%= render partial: "quiz", locals: { url: new_flex_quiz_path, method: :post } %>  

And my edit view:

<%= render "quiz", url: edit_flex_quiz_path(@flex_quiz), method: :put  %>  

Here are the route paths:

         Prefix Verb   URI Pattern                    Controller#Action              ...       flex_quiz_index GET    /flex_quiz(.:format)           flex_quiz#index                  POST   /flex_quiz(.:format)           flex_quiz#create    new_flex_quiz GET    /flex_quiz/new(.:format)       flex_quiz#new   edit_flex_quiz GET    /flex_quiz/:id/edit(.:format)  flex_quiz#edit        flex_quiz GET    /flex_quiz/:id(.:format)       flex_quiz#show                  PATCH  /flex_quiz/:id(.:format)       flex_quiz#update                  PUT    /flex_quiz/:id(.:format)       flex_quiz#update                  DELETE /flex_quiz/:id(.:format)       flex_quiz#destroy  

Can anyone suggest how to fix this? I have looked at several similar posts (like this and this) but since I'm using partials the solution here is going to have to be a bit different.

Ruby on rails bootstrap css js working but not found

Posted: 30 Apr 2016 06:37 AM PDT

I have a rails application which I added the bootstrap gem

first I added this two gems

gem 'bootstrap'  gem 'sprockets-rails', :require => 'sprockets/railtie'  

which installed this packages

Using bootstrap 4.0.0.alpha3  Using sprockets 3.6.0  

After I modified application.scss to

// Custom bootstrap variables must be set or import before bootstrap itself.  @import "bootstrap";  

Then I left application.js like this

// This is a manifest file that'll be compiled into application.js, which will include all the files  // listed below.  //  // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,  // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.  //  // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the  // compiled file.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details  // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require turbolinks  //= require tether  //= require bootstrap-sprockets  //= require_tree .  //= require_self  

Lastly my application.html.erb is this

<!DOCTYPE html>  <html>  <head>    <title>Squirm</title>    <%= stylesheet_link_tag    "bootstrap"  %>   <%= javascript_include_tag "bootstrap" %>   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>   <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>   <%= csrf_meta_tags %>  </head>  <body>    <%= render 'partials/navbar' %>      <div class="container">      <%= yield %>    </div>    </body>  </html>  

Bootstrap seems to we working, but in the Google Chrome console seems not to be found

enter image description here

Rails5/Devise 4.0.1 Overriding Confirmations controller to allow password at activation: Token Blank

Posted: 30 Apr 2016 06:35 AM PDT

Using the wiki tutorial, I've implemented the gradual engagement approach to registration.

Now, after clicking the "confirm" link in email, the password page will say "Confirmation token can't be blank".

It's being submitted in the form, I can see the params passed in the log, but it's a hash params[:user][:confirmation_token], not params[:confirmation_token].

How can I remedy this issue?

Rails Tutorial- cannot get rails to recognize route

Posted: 30 Apr 2016 06:29 AM PDT

I am new to programming in general, someone referred me to railstutorial.org.

Specs: I am working on a cloud9 IDE, as suggested in the tutorial.

Information: I am on 1.3 of the rails tutorial, which is setting the root route. The problem was initially my route did not effect the server launch (root page was still ruby default, not to 'application#hello'). Here are the files that the tutorial said to edit.

routes.rb

Rails.application.routes.draw do  root to: 'application#hello'  end  

application_controller.rb

class ApplicationController < ActionController::Base  protect_from_forgery with: :exception  def hello  render text: "Hello, world!"  end  end  

There are a lot of comments that were defaulted into the files that I left out.

I have followed the instructions precisely. After I first had trouble, I thought I may have made an installation error, so I deleted my IDE and restarted, paying extreme attention to detail, especially versions.

I have tried $ rake routes, and my understanding it gives the message:

You don't have any routes defined!  

That leads me to believe that the problem is the routes.rb file. I have tried changing the syntax to:

root to: 'application#hello'  

I don't know a whole lot, such as how it would work using application, so I also tried:

root 'ApplicationController#hello'  

and

root to: 'ApplicationController#hello'  

These all result in the no routes defined message. I have no idea what is going on.

Thanks for any input or help!

Rails 4.2.6 FactoryGirl with polymorphic association

Posted: 30 Apr 2016 06:13 AM PDT

I have a problem setting up factories for my polymorphic associations with FactoryGirl. My model and factory setup looks like this:

class Address < ActiveRecord::Base    belongs_to :addressable, polymorphic: true  end    class Customer < ActiveRecord::Base    has_one :address, as: :addressable  end     factory :address do        village Faker::Address.city        upazilla Faker::Address.street_name        ward Faker::Address.street_address        district Faker::Address.state        association :addressable  end      factory :customer ,class: Customer do         recharge_token 10         date_of_birth Faker::Date.backward(100)        manager        after(:create) do |customer|            customer.address = create(:address, addressable: customer)          #create( :address, addressable: customer)        end       end  

The test suite breaks with the following error message

 vendor/cache/ruby/2.2.0/gems/factory_girl-4.7.0/lib/factory_girl/linter.rb:12:in `lint!': The following factories are invalid: (FactoryGirl::InvalidFactoryError)   * address - Factory not registered: addressable (ArgumentError)  

This is exactly my problem but unfortunately his solution is not working for me. Thanks you all for your time!

Show brings up a list of data

Posted: 30 Apr 2016 06:07 AM PDT

I am trying to show a list of all the items I've created. (Called "join") In the show.html.erb, I wrote

<%= @join = Join.all %>    <%= @join.each do |join| %>    <%= join.email %>  <% end %>  

And It's working, but when I go to the page I get a bunch of data that says: #<Join::ActiveRecord_Relation:0x007fbca99f12b8> sbhenrichs@gmail.com [#<Join id: 1, email: "sbhenrichs@gmail.com", created_at: "2016-04-30 12:48:16", updated_at: "2016-04-30 12:48:16">] Does anybody know how to get rid of that?

Rails 4 Image gallery options? [on hold]

Posted: 30 Apr 2016 06:41 AM PDT

I am wondering how to display multiple images when a user clicks on a thumbnail using Rails 4.

For example, a user clicking on a thumbnail in an image gallery full of shoes will display the image of the shoe in a dimmed pop-up window, but also allow the user to navigate left and right from that one thumbnail, to see multiple images of the shoe taken at different angles; the multiple angles of the shoes should be hidden unless clicked on by the user.

I have heard of the paperclip gem, but the tutorials I have seen seem to focus more on single images displayed in a gallery.

stderr /usr/local/bin/bundle: argument list too long while bundle install

Posted: 30 Apr 2016 05:06 AM PDT

I am using ansible to do deployment for my rails app. The problem is when a new gem is added and the ansible runs bundle install, it gives the following error:

stderr /usr/local/bin/bundle: argument list too long  /usr/local/bin/bundle: line 7: /usr/local/bin/bundle: success  

The ansible task to do bundle install is

- name: Bundle install    command: 'bundle install --deployment --without development test'    register: bundler    args:      chdir: '/home/ubuntu/myproject'  

I am using rvm to manage ruby version. Using ruby-2.2.1 and I have set rvm to use gemset of myproject i.e. rvm use ruby-2.2.1@myproject.

The .rvm/gems/ directory have ruby-2.2.1/ ruby-2.2.1@global/ ruby-2.2.1@myproject/

I have specified passenger_ruby /home/ubuntu/.rvm/wrappers/ruby-2.2.1@myproject/ruby

This happens only when new gem is added in Gemfile, when there is only code update, everything works fine. If I run bundle install explicitly doing ssh to corresponding instance, it works fine and install the gem. Any help and suggestion on this?

Rails, CarrierWave and AngularJS ngFileUpload

Posted: 30 Apr 2016 04:41 AM PDT

I have been trying to upload images for the past couple of hours using ngFileupload and had no luck, I am building a SPA (for learning purposes) using rails and angularJS for upload I am using Carrierwave.

Here goes the problem, I have no clue what I am doing at this stage I have added Ng-file-uploader to my app as follows:

var app = angular.module('myApp', ['ui.router', 'ngResource', 'templates', 'Devise', 'ngAnimate', 'ngFileUpload']);  

and in the projectCtrl it is as follows:

app.controller('NewProjectCtrl', ['$scope', 'ProjectsSvc', '$state','Upload', function($scope, ProjectsSvc, $state, Upload){    $scope.upload = function (file) {           Upload.upload({               url: '/projects',               data: {file: file, 'filename': $scope.project.title}           }).then(function (resp) {               console.log('Success ' + resp.config.file.name + 'uploaded. Response: ' + resp.data);           }, function (resp) {               console.log('Error status: ' + resp.status);           }, function (evt) {               var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);               console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);           });       };    $scope.project = new ProjectsSvc();    $scope.addProject = function() {      $scope.upload($scope.file);      $scope.project.$save(function(){});    };  

Now everytime I try to create a new project I get the following error

enter image description here

Any help would be greatly appreciated.

P.S. two weeks ago I was clueless when it came to JavaScript and AngularJS

RoR app - 'gem install mysql' error when running 'cap production deploy:initial'

Posted: 30 Apr 2016 04:18 AM PDT

I'm attempting to deploy my Ruby on Rails app to a DigitalOcean droplet and I've been using this guide on how to do so, I followed a guide previously on how to deploy (a youtube video tutorial) but it didn't work so I've attempted this written guide. Everything has been working so far except when I attempt to deploy using cap production deploy:initial I get the following:

An error occurred while installing mysql2 (0.4.4), and Bundler cannot continue. Make sure that `gem install mysql2 -v '0.4.4'` succeeds before bundling.  

Along with three other errors; see screenshot.

enter image description here

How do I make sure it succeeds before bundling during the deploy? Is there any files I need to look at to make sure I've done everything correctly? Let me know if I need to include any other files.

How to make charts in rails using csv/json files stored in database?

Posted: 30 Apr 2016 03:55 AM PDT

I have some csv/json data sets and a State (province of country) model in my appication. Now I wanna make another model Data and gonna relate it as follow :

state --> has_many:data

Data Model attributes must be the files in csv/json format My state model has one attribute :

name:string

now when the current user's location matches the state model's name string I want to show the graphs in the profile page of user the graphs must be from DATA model's(contains csv / json files).

Question 1: How do I store csv/json files in model ?

Question 2: How do I make charts using csv and json files contained in rails model ?

Beanstalkd BackBurner not starting

Posted: 30 Apr 2016 03:13 AM PDT

Whenever I am starting backburner I get following error but console shows daemon started successfully /Users/someuser/.rvm/rubies/ruby-2.0.0-p643/lib/ruby/2.0.0/uri/generic.rb:214:in initialize': the scheme beanstalk does not accept registry part: : (or bad hostname?) (URI::InvalidURIError) from /Users/someuser/.rvm/rubies/ruby-2.0.0-p643/lib/ruby/2.0.0/uri/common.rb:218:innew' from /Users/someuser/.rvm/rubies/ruby-2.0.0-p643/lib/ruby/2.0.0/uri/common.rb:218:in parse' from /Users/someuser/.rvm/rubies/ruby-2.0.0-p643/lib/ruby/2.0.0/uri/common.rb:747:inparse' from /Users/someuser/application/vendor/ruby/2.0.0/gems/backburner-0.4.6/lib/backburner/connection.rb:46:in `beanstalk_host_and_port'

Error when trying get index of list nested route Rails "unexpected tIVAR"

Posted: 30 Apr 2016 03:37 AM PDT

I want to get a list of all the reviews that belong to a, which belongs a category. I'm getting an error when trying to get a list of all the reviews in a JSON file (it's a API application): "/Code/Rails/videogame_reviews/app/controllers/reviews_controller.rb:6: syntax error, unexpected tIVAR, expecting '(' @reviews = @category.@game.reviews ^".

Could anybody explain why this is failing? @reviews = Reviews.all is working but shows all the reviews.

This the is ReviewsController

def index    @game = Game.find(params[:game_id])    @category = Category.find(params[:category_id])    @reviews = @category.@game.reviews    respond_to do |f|      f.html      f.json { render json: { category: @category, game: @game, reviews: @reviews} }    end  end  

I've made a copy from the GamesController index which is working

 def index    @category = Category.find(params[:category_id])    @games = @category.games    respond_to do |f|      f.html      f.json { render json: { category: @category, games: @games } }    end  end  

Here is the Reviews model

class Review < ActiveRecord::Base    belongs_to :game    validates_presence_of :comment  end  

This is the Game model

class Game < ActiveRecord::Base    belongs_to :category    has_many :reviews    validates_presence_of :title, :category  end  

And this is the Category model

class Category < ActiveRecord::Base    validates_presence_of :name    has_many :games  end  

Here is the routes for the reviews

resources :categories do    resources :games do       resources :reviews    end  end  

How to cache an array using Active Model Serializers (0.8)?

Posted: 30 Apr 2016 02:31 AM PDT

On an individual Active Model Serializer you can specify the cache key within your serializer, i.e.

Caching a single object using AMS

class OrgSerializer < ActiveModel::Serializer    cached     delegate :cache_key, to: :object  end  

Array caching

I need to deliver an array of these objects:

array_json = ActiveModel::ArraySerializer.new(Org.all.limit(50)).to_json  

Rather than do 50 cache hits to construct the array I want to do a single cache hit and expire it when any of the array elements expires.

How to cache the array (and construct the key)?

I therefore want a cache key for the array that is made up of the individual object IDs and their last-updated at date like this:

def cache_key_for_collection collection    keys = collection.collect{|element| "#{element.id}#{element.updated_at}" }    keys.join ""  end  

How can you do this with AMS (0.8)?

Does the AMS array serializer allow for this or is it something that needs to just be done manually? Is there a way to declare that you want caching and how the key should be constructed?

If it doesn't do it then what would be the neatest way to manually construct the cache/key?

awesome_nested_set (2.1.5) duplicate issue

Posted: 30 Apr 2016 02:27 AM PDT

awesome_nested_set gem is behaving weird, what I understand is lft and rgt values should be unique for each record. Otherwise tree structure will not be proper. However, I can see duplicate records within a table.

Below is the output of table.

select lft,rgt from groups where company_id=1;

Table Output

I want the values should be unique, I have checked for validation while inserting records, but awesome_nested_set gem updates the value for lft, rgt periodically hence the already existing data of records gets change. Not really sure how the gem internally works.

How can i use Soundmanager2 with ruby on rails

Posted: 30 Apr 2016 02:17 AM PDT

i'm a bit new to ruby on rails, i have uploaded the js scripts and the swf to my assets, i have also added the required lines to the appliction.js but when i put the script in my html.erb it does nt work Thanks in advance

Rails youtube thumbnail with scaffold

Posted: 30 Apr 2016 02:05 AM PDT

I have made a post scaffold . I want to extract the URL FROM the description column in which they can write anything including a youtube URL. Then I want to get a thumbnail place it with an image tag . and when people click on that image tag I want it to direct to the youtube URL

How To Convert Rails Application Into An Actual Site

Posted: 30 Apr 2016 01:52 AM PDT

I built a simple todo list application on Rails. I built it through Team Treehouse. It was one of the courses. I am wondering how would I convert it to a site. The reason being is because it would be a nice to add to my portfolio (I have yet to style it though). Would I simply upload the application to my github then go through such as I would to create a website through Github pages?

I plan to buy a url for it. I am just simply trying to gauge out how would I approach converting it into a site. My apologies, it is a noob question.

Ajax "link_to" sending multiple requests controller requests when clicked really fast(Rails 4)

Posted: 30 Apr 2016 02:25 AM PDT

Before I explain my problem, I will provide the relevant code for context. I have a Teams Model which is associated to a Scoreboard Model. The problem at hand is associated with Teams.

The View for Teams Index

<div class="team-list">      <%= render @scoreboard.teams.reject(&:new_record?) %>  </div>  

The Partial for @scoreboard.teams

<div class="row team-div" id="team_<%=team.id%>">      <div class="col-xs-3 team-div-1"> <%= team.name %> </div>         <%= link_to (edit_scoreboard_team_path(@scoreboard, team)), remote: true do %>         <div class="col-xs-6 team-data">          <div class="row">              <div class="col-xs-4 team-div-2"><%= team.win %> </div>              <div class="col-xs-4 team-div-2"><%= team.loss %> </div>              <div class="col-xs-4 team-div-2"><%= team.tie %></div>          </div>         </div>      <% end %>        <div class="col-xs-1 team-div-2">          <%= team.win + team.loss + team.tie %>      </div>        <div class="col-xs-1 team-div-2">        <% total_games = team.win.to_i + team.loss.to_i + team.tie.to_i %>      <% if total_games == 0 %>       <%= "N/A" %>      <% else %>       <%= (team.win.to_i/(total_games).to_f*100).round(2) %><%="%"%>      <% end %>      </div>        <div class="col-xs-1 team-setting">               <i class="fa fa-trash-o fa-lg" aria-hidden="true"></i>       </div>    </div>  

The link_to I'm having trouble with is for the Edit Method.

Team#edit Controller Method

  def edit      @scoreboard = Scoreboard.find(params[:scoreboard_id])      @team = @scoreboard.teams.find(params[:id])      respond_to do |format|       format.html {redirect_to scoreboard_url(@team.scoreboard_id)}       format.js       end     end  

The edit.js.erb file

$("#team_<%=@team.id%>").hide();  $("#team_<%=@team.id%>").before("<%= j render 'teamedit'%>");  

Now, to explain the problem.I am in the development environment. In a perfect world, I would like to click on the link_to for edit and have the specific team div disappear right away(only so I can't click on it again) and render the edit form for that Team. However, during slow loads(happens a lot), I can click on the link_to two or three times and it calls multiple controller requests to the edit method. The problem with this is that the Jquery is also executed as many times as I clicked and I end up with 2 or 3 forms for the same element.

For example, these are the log files when I click really fast on the link_to for Team with Id=50:

Started GET "/scoreboards/1/teams/50/edit" for 99.239.140.167 at 2016-04-30 08:07:52 +0000  Processing by TeamsController#edit as JS    Parameters: {"scoreboard_id"=>"1", "id"=>"50"}    User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]    Scoreboard Load (0.3ms)  SELECT  "scoreboards".* FROM "scoreboards" WHERE "scoreboards"."id" = $1  ORDER BY "score oards"."created_at" DESC LIMIT 1  [["id", 1]]    Team Load (0.3ms)  SELECT  "teams".* FROM "teams" WHERE "teams"."scoreboard_id" = $1 AND "teams"."id" = $2 LIMIT 1  [["scoreboard_id", 1], ["id", 50]]    Rendered teams/_teamedit.html.erb (3.1ms)    Rendered teams/edit.js.erb (7.1ms)  Completed 200 OK in 35ms (Views: 27.6ms | ActiveRecord: 1.2ms)      Started GET "/scoreboards/1/teams/50/edit" for 99.239.140.167 at 2016-04-30 08:07:52 +0000  Processing by TeamsController#edit as JS    Parameters: {"scoreboard_id"=>"1", "id"=>"50"}    User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]    Scoreboard Load (0.4ms)  SELECT  "scoreboards".* FROM "scoreboards" WHERE "scoreboards"."id" = $1  ORDER BY "scoreboards"."created_at" DESC LIMIT 1  [["id", 1]]    Team Load (0.3ms)  SELECT  "teams".* FROM "teams" WHERE "teams"."scoreboard_id" = $1 AND "teams"."id" = $2 LIMIT 1  [["scoreboard_id", 1], ["id", 50]]    Rendered teams/_teamedit.html.erb (2.1ms)    Rendered teams/edit.js.erb (5.6ms)  Completed 200 OK in 30ms (Views: 24.2ms | ActiveRecord: 1.0ms)  

Each request rendered edit.js.erb so I ended up with two forms. How can I make it possible that no matter how many times I am able to click on the "link_to" before it disappears, only one edit-form for that resource is generated?

In Rails How to display errors in my comment form after I submit it?

Posted: 30 Apr 2016 07:01 AM PDT

I have a very straight-forward task to fulfil --- just to be able to write comments under posts and if the comments fail validation display error messages on the page.

My comment model uses a gem called Acts_as_commentable_with_threading, which creates a comment model after I installed.

On my post page, the logic goes like this:

Posts#show => display post and a form to enter comments => after the comment is entered, redisplay the Post#show page which has the new comment if it passes validation, otherwise display the error messages above the form.

However with my current code I can't display error messages if the comment validation fails. I think it is because when I redisplay the page it builds a new comment so the old one was erased. But I don't know how to make it work.

My codes are like this:

Comment.rb:

class Comment < ActiveRecord::Base    include Humanizer    require_human_on :create      acts_as_nested_set :scope => [:commentable_id, :commentable_type]      validates :body, :presence => true    validates :first_name, :presence => true    validates :last_name, :presence => true      # NOTE: install the acts_as_votable plugin if you    # want user to vote on the quality of comments.    #acts_as_votable      belongs_to :commentable, :polymorphic => true      # NOTE: Comments belong to a user    belongs_to :user      # Helper class method that allows you to build a comment    # by passing a commentable object, a user (could be nil), and comment text    # example in readme    def self.build_from(obj, user_id, comment, first_name, last_name)       new \          :commentable => obj,          :body        => comment,          :user_id     => user_id,          :first_name  => first_name,          :last_name   => last_name    end  end  

PostController.rb:

class PostsController < ApplicationController    before_action :authenticate_user!, except: [:index, :show]      def show        @post = Post.friendly.find(params[:id])        @new_comment = Comment.build_from(@post, nil, "", "", "")    end  end  

CommentsController:

class CommentsController < ApplicationController    def create      @comment = build_comment(comment_params)      respond_to do |format|          if @comment.save              make_child_comment              format.html              format.json { redirect_to(:back, :notice => 'Comment was successfully added.')}          else              format.html              format.json { redirect_to(:back, :flash => {:error => @comment.errors}) }          end      end  end    private      def comment_params          params.require(:comment).permit(:user, :first_name, :last_name, :body, :commentable_id, :commentable_type, :comment_id,              :humanizer_answer, :humanizer_question_id)      end        def commentable_type          comment_params[:commentable_type]      end        def commentable_id          comment_params[:commentable_id]      end        def comment_id          comment_params[:comment_id]      end        def body          comment_params[:body]      end        def make_child_comment          return "" if comment_id.blank?            parent_comment = Comment.find comment_id          @comment.move_to_child_of(parent_comment)      end        def build_comment(comment_params)          if current_user.nil?              user_id = nil               first_name =  comment_params[:first_name]              last_name = comment_params[:last_name]          else              user_id = current_user.id              first_name = current_user.first_name              last_name = current_user.last_name          end          commentable = commentable_type.constantize.find(commentable_id)          Comment.build_from(commentable, user_id, comment_params[:body],                      first_name, last_name)      end  end  

comments/form: (this is on the Posts#show page)

<%= form_for @new_comment do |f| %>      <% if @new_comment.errors.any? %>      <div id="errors">          <h2><%= pluralize(@new_comment.errors.count, "error") %> encountered, please check your input.</h2>            <ul>              <% @new_comment.errors.full_messages.each do |msg| %>                  <li><%= msg %></li>              <% end %>          </ul>      </div>    <% end %>  <% end %>  

How can I allow user put a website link into text_area and display the link that is clickable in Rails 4?

Posted: 30 Apr 2016 01:43 AM PDT

And user can put a description of the party. Also the user can type any link as description.

However, after user saved, the link he typed is not clickable. I have to copy the link address and paste into browser to go to the site.

Below is the views/parties/_form.html.erb:

<%= form_for(@party, multipart: true) do |f| %>    <div id="error_explanation">        <ul><%= @party.errors.full_messages.first if @party.errors.any? %></ul>    </div>      <div class="field">      <%= f.label :title %><br>      <%= f.text_field :title, :class => "form-control", placeholder: 'Type title' %>    </div>      <div class="field">      <%= f.label :location %><br>      <%= f.text_field :location, :class => "form-control", placeholder: 'Type location' %>    </div>      <div class="field">      <div class="form-group">          <label>time</label>          <%= f.datetime_select :time %>      </div>    </div>      <div class="field">      <%= f.label :description %><br>      <a style="text-decoration:none;" title="Suggest!" data-toggle="popover" data-trigger="hover" data-placement="top" data-content="Ticket? Any Link? Tell me more!"><%= f.text_area :description, :class => "form-control", :rows => "3" %></a>    </div>      <div class="field">        <%= f.label :image %><br>        <%= f.file_field :image %>    </div>    <p>    </p>    <div class="actions">      <%= f.submit "Let's post it", :class => "btn btn-primary", :id => "load", 'data-loading-text' => "Uploading...".html_safe %>    </div>    <p>    </p>  <% end %>  

How can I convert the link to clickable link if user typed any link? when show its description?

For example, if a user typed,  "Hi we have party tomorrow at 12:00 pm.  Also more information is at www.facebook.com/samplepartybrabrabra  ticket is $5 per person."  

Ruby on Rails where query with nesting relations

Posted: 30 Apr 2016 01:09 AM PDT

I learned how to use where query with relations from this question.

Ruby on Rails where query with relations

However, I still can't make it right with this nesting case. How can I make Summaries controllers index work?

Model

User    has_many :projects, dependent: :destroy    has_many :reasons, through: :projects    has_many :summaries, through: :projects, source: :reasons    has_many :entries, through: :projects    Project    belongs_to :user    has_many :reasons    has_many :entries, through: :reasons    Reasons    belongs_to :project    has_many :entries, dependent: :destroy     has_many :summaries, dependent: :destroy     Summary    belongs_to :reason    Entry    belongs_to :reason  

EntriesController

  # GET /entries    def index      entries     = current_user.entries      updated_at  = params[:updated_at]        # Filter with updated_at for reloading from mobile app      if updated_at.present?          # THIS WORKS!!!!!!!!!!!!!        entries = entries.joins(:reason).where("reasons.updated_at > ?", Time.at(updated_at.to_i))        # Get all non deleted objects when logging in from mobile app      else        entries = entries.where(deleted: false)      end        render json: entries    end   

SummariesController

  # GET /summaries    def index      summaries   = current_user.summaries      updated_at  = params[:updated_at]        # Filter with updated_at for reloading from mobile app      if updated_at.present?              #THIS DOES NOT WORK, what can I do?????        summaries = summaries.joins(:reason).where("reasons.updated_at > ?", Time.at(updated_at.to_i))            # Get all non deleted objects when logging in from mobile app      else        summaries = summaries.where(deleted: false)      end        render json: summaries    end    

@Error log on iOS

Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: internal server error (500)" UserInfo={NSUnderlyingError=0x1481b9030 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"

@Error log on Heroku

[1m[36mUser Load (2.0ms)[0m [1mSELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1[0m 2016-04-30T07:48:18.909397+00:00 app[web.1]: Completed 500 Internal Server Error in 4ms (ActiveRecord: 2.0ms) 2016-04-30T07:48:18.910250+00:00 app[web.1]: ActiveRecord::ConfigurationError (Association named 'reason' was not found on Reason; perhaps you misspelled it?):

Rspec tests are slower when I change the position of the validations in the model

Posted: 30 Apr 2016 12:34 AM PDT

I have a big rails application in which I have tons of models. I have reorganized the content of the models to follow a common pattern (positions of the fields, constants, relations, validations, hooks and so on on all files). After finishing of doing this process, I have realized that the tests are slower (a controller test which takes 40 seconds, now it uses more than 1 minute).

I have spent a lot of time trying to find the reason and finally I have found the problem. When I declare the validations after the relations, it takes more time to pass the tests (and the performarcen of the application is worse):

class Model    include Mongoid::Document      ## Fields    ...      ## Relations    ...      ## Validations    ...  end  

On the opposite, if I declare the relations after the validations, the performance is the same as previous:

class Model    include Mongoid::Document      ## Fields    ...      ## Validations    ...      ## Relations    ...  end  

I can't find a reason of this behaviour. Maybe it is because I am using mongoid 3 and this type of things are not happening with the next versions. However, for me it is more reasonable to have the relations before the validations because some of the validations reference to the relations.

calling function in rails

Posted: 30 Apr 2016 12:50 AM PDT

I try to use a function in Rails but I keep getting the same error. I tried a bit of everything!!

I define the function in my model. It is a big calculation but I completely simplified it too, and still get the same error!!

My function in my model: Original function:

class Customer < ActiveRecord::Base    belongs_to :partner      #    public      def find_next_user_value(user_sequence)     last_user_value = User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.last_used }      user_prefix = User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_prefix }      user_length = User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_length }      User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_prefix } + number_to_string(User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.last_used } +=1).ljust(User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_length } - User_Sequences.where(:user_sequence_name=> user_sequence).map{|element| element.user_sequence_prefix }.bytesize,"0")    end  end  

Simplified version:

class Customer < ActiveRecord::Base    belongs_to :partner      #    public    def find_next_user_value      "TEST2"    end  end  

The call from the controller:

  def new     @customer = Customer.new(partner_id: @partner.id, customer_name: @partner.name, partner_number: @partner.number, number: @customer.find_next_user_value("Customer_Number"))    end  

simplified:

  def new      @customer = Customer.new(partner_id: @partner.id, customer_name: @partner.name, partner_number: @partner.number, number:  @customer.find_next_user_value)    end  

In both case I get the same error:

undefined method `find_next_user_value' for nil:NilClass

What am I doing wrong?

Thank you!!!!!

How to dynamically set the path of a link based on two different inputs?

Posted: 30 Apr 2016 12:51 AM PDT

I have a model Movie and I have a page for comparing two movies. I use params A and B to set the two movies:

<%    @movie1 = Movie.find_by(title: params[:A])    @movie2 = Movie.find_by(title: params[:B])  %>  

The left side of the page shows the "A" movie and the right side shows the "B" movie.

There's an option to remove the two current movies and input new ones. Right now the system I have is this: the "A" and "B" sides of the page both have a drop-down menu with clickable suggestions that come up as the user types, and clicking on a suggestion on the A side links to the same page except with params[:A] replaced, and vice versa.

For example, clicking on "Harry Potter" under the A side would use this link: <%= link_to "Harry Potter", compare_path(A: "Harry Potter", B: params[:B]) %>

But this way, the user has to wait for the page to load after selecting each movie. I want the user to be able to input both movies, and then press a button to reload the page with the new parameters.

So I would need some kind of "Run Comparison" link button, and clicking on a suggestion would have to reset that link's path, probably using jQuery. The trick is, the "A" suggestions would have to take into account the most recent "B" suggestion, and vice versa.

For example, if both selections are empty, and I select "Harry Potter" on the A side, then the link's path would be compare_path(a: "Harry Potter", b: ""), but then if I select "The Ring" on the B side, then the new path should be compare_path(a: "Harry Potter", b: "The Ring"). And then if I change my mind and select "Bewitched" on the A side, then the path is re-updated to compare_path(a: "Bewitched", b: "The Ring")

I'm completely lost. Anyone have any idea how to accomplish this?

Rails Routes - Id and name with spaces replaced with hyphens

Posted: 30 Apr 2016 04:02 AM PDT

I am developing my first application in rails. I went through the Rails Routing from the Outside In documentation but unable to figure out how to setup the following route.

I have a ClientsController and the for the show action I want to display the client's first and last name with spaces replaced with hyphens, in the url.

Instead of the following

localhost:3000/clients/1

the link should be (first name : john, last name : doe)

localhost:3000/clients/1/john-doe

Sum of all amount if charge dates are the same in Stripe

Posted: 30 Apr 2016 02:07 AM PDT

I'm iterating over a stripe charge object and I want to sum up the amount total for each day.

# Returns an array object of charges for a customer  @customer_charges = Stripe::Charge.all(:customer => current_user.stripeid)  

Views:

<% @customer_charges.map do |c| %>    On Monday, you were charged a total of <%= c.amount %>  <% end %>  

Surely the above does nothing more than output lines of each charges but not the sum for the day. The difficulty I face is to sum up all charges for each day. Could someone point me in the right direction?

The output would be like:

"On Monday, you were charged a total of 200000"  "On Tueesday, you were charged a total of 500000"  etc...  

Instead of:

On Monday, you were charged a total of 100000"  On Monday, you were charged a total of 100000"  etc...  

My view looks messy with lines of if statements to compare dates and that does not look right.

How much Rails knowledge do I need to develop a Shopify App?

Posted: 29 Apr 2016 11:50 PM PDT

Can I learn Ruby and Rails on Codecademy and build a Shopify App?

Advance Active Record Joins

Posted: 29 Apr 2016 11:39 PM PDT

I have the following models

Items   Customisations  Property Maps  

with Associations like so --

**Customizations**  belongs_to :item  has_many :property_maps, as: :mappable     **Items**    has_many :customizations    has_many :property_maps, as: :mappable    **Property Maps**  belongs_to :mappable, polymorphic: true  

I've implemented a pretty decent filtering system taking into consideration just Items and properties like so --

    def self.filter_in_properties(property_ids, group_name)             joins(:property_maps).joins('JOIN property_maps '+group_name+' ON '+group_name+'.mappable_id = items.id  AND '+group_name+'.property_id IN ('+property_ids.to_s.tr('[', '').tr(']', '').tr('"', '') +')')      end  

and I call them in the controller like so --

@items_without_pagination.filter_in_properties(params[:color_filter], 'color_filter').uniq  

How can I do build out a filtering system so that when for example a user searches for the color red, it not only returns items that have the property red but also return items which have customizations with the property red?

Friday, April 29, 2016

How to nest namspaced resources and avoid double namespacing - uninitialized constant ActsAs::ActsAs | Fixed issues

How to nest namspaced resources and avoid double namespacing - uninitialized constant ActsAs::ActsAs | Fixed issues


How to nest namspaced resources and avoid double namespacing - uninitialized constant ActsAs::ActsAs

Posted: 29 Apr 2016 07:09 AM PDT

I have two namespaced models in a Rails app - ActsAs::Comments and ActsAs::Likes. Both are polymorphic, and belong to several different parent models. Improtantly for this question, Likes can belong to a Comment.

So my routes look something like this

namespace :acts_as do    resources :comments do      namespace :acts_as do        resources :likes, only: :create      end    end  end   resource :other_objects do    namespace :acts_as do      resources :likes, only: :create    end  end  

I then have a shared partial, called in the parent object's view, for adding likes.

<%= link_to 'Like',     polymorphic_path(       [ @object, ActsAs::Like.new ],       like: { likable_type: @object.class.name, likable_id: @object.id }     ) %>  

This work's fine for OtherObjects, but not for Comments.

Rake routes shows

acts_as_comment_acts_as_likes    POST       /acts_as/comments/:comment_id/acts_as/likes(.:format)  acts_as/acts_as/likes#create  # note the double namespacing of the controller  

Clicking 'like' gives

ActionController::RoutingError - uninitialized constant ActsAs::ActsAs:  

What is the correct way to set this up and avoid this double namespacing of the controller?

Running rails project on heroku

Posted: 29 Apr 2016 07:13 AM PDT

I a little bit new for heroku and postgresql and dont know how works translting from mysql to postgresql. My application was developed on mysql and to run it from heroku i made some steps: 1. Added a gem 'pg' and gem 'rails_12factor' like that:

group :production do    gem 'pg'    gem 'rails_12factor'  end  

And bundle it without production 2. I also changed my database.yml into: (Also i have question, how can i use mysql in devolepment and postgre in production?)

# PostgreSQL. Versions 8.2 and up are supported.  #  # Install the pg driver:  #   gem install pg  # On OS X with Homebrew:  #   gem install pg -- --with-pg-config=/usr/local/bin/pg_config  # On OS X with MacPorts:  #   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config  # On Windows:  #   gem install pg  #       Choose the win32 build.  #       Install PostgreSQL and put its /bin directory on your path.  #  # Configure Using Gemfile  # gem 'pg'  #  default: &default    adapter: postgresql    encoding: unicode    # For details on connection pooling, see rails configuration guide    # http://guides.rubyonrails.org/configuring.html#database-pooling    pool: 5  

But! When i tryed to work via heroku(downloading works fine) my dynamic pages wasnt working, and i get this errors: Errors

So, i guessed that DB just doesnt migrate, OK, i runned via console this: heroku run rake db:migrate --app name
Aaand i now i have this error:

rake aborted!  StandardError: An error has occurred, this and all later migrations canceled:    PG::UndefinedTable: ERROR:  relation "schoolings" does not exist  : ALTER TABLE "students" ADD CONSTRAINT "fk_rails_e33c769d03"  FOREIGN KEY ("schooling_id")  REFERENCES "schoolings" ("id")   

My questions:

1. Why it happens? Did i miss some steps when deployed my app?

2. How can i separate production and dev DB in deployment.yml?

Thanks, for any help!

comparing one element in an ActiveRecord array to all others ruby on rails

Posted: 29 Apr 2016 07:00 AM PDT

I have a simple ActiveRecord query along the lines of this:

similar_changes = Notification.where(change_owner: 'foo1', change_target: 'foo2', change_cancelled: false)  

Each notification object has a field change_type and I have another function that checks one Notification's change_type with one other Notification for inverse changes (changes that undo each other in the context of my application)

I need to take this Notification's change_type and compare it against all others in the array. I have to reference the objects like so: similar_changes[0]['change_type'] where the first index is each ActiveRecord in the array and the second is the dictionary that specifies which property in the Notification object.

I have a feeling I could do this manually with two nested loops and if statements, but I also know Ruby and I feel like this is something that it should have built in.

Am I wrong, or is there a better way to do this?

For reference (if it matters) here is how I check for inverse changes:

def inverse?(possible_inverse_change)   is_inverse = false   change_types = YAML.load_file(File.join(NotificationManager::Engine.root, 'config/change_types.yaml'))   if self.change_type == change_type[possible_inverse_change]['inverse']    is_inverse = true   end   return is_inverse  end  

wkhtmltopdf not corresponding size after generating pdf Rails

Posted: 29 Apr 2016 06:49 AM PDT

Iv got a small problem using wkhtmltopdf (wicked_pdf) with rails.

This is my pdf after generating.

enter image description here

and this is my show action. respond_to do |format| format.html

  format.pdf do      render :pdf      => "resume",             :encoding => "utf-8",             :template => "resumes/show/#{template_id}",             #:orientation                    => 'Landscape',                 #:show_as_html                   => params[:debug].present?,             :disable_smart_shrinking        => true,             #:disable_javascript             => true,             :margin   => {:top => 5, :bottom => 5, :right => 5, :left => 5}    end  end  

As you can see this is an A4 size page (by default) and Im giving 5 mm margin on each side. The A4 paper have in width 210 mm. Now after Im giving margin of 5mm I'm left with 200mm right? OK

In css Im giving to this container a max width of 200mm + those 10 mm of margin should be 210 mm (the size of an A4 page)

.page-container{      background: white;      width: 200mm;      max-width: 200mm;      display: block;    }  

As you can see in the pic, the generated pdf has way way more mm in width then 210. Any ideas why and how to fix it?

If Im setting the width to 100% it will work but that doesnot mean that the width will be 210 mm.

Whitelist params - how to allow n level nesting of self relationship?

Posted: 29 Apr 2016 06:29 AM PDT

I've got a use case where employee hierarchies are going to be stored as strings so they can be retrieved in json. (This is a POC, so just a hack for SQLite for now).

How can I permit n level of nested objects? In the following example :h_data is json coming in the request body. Right now I'm hacking it to 3 levels of hierarchy with:

params.require(:hierarchy_version).permit(:name, :creator_id, :top_employee_id, :h_data => [:name, :id, :salary, :manager_id, :direct_reports => [:name, :id, :salary, :manager_id, :direct_reports => [:name, :id, :salary, :manager_id, :direct_reports]]])  

How to Encrypt data in ruby same as SecretKeySpec?

Posted: 29 Apr 2016 06:19 AM PDT

I am trying to encrypt a string in ruby using Cipher with AES algorithm. I have example written in Java. I have taken help from this example and written code in Java but not able to get the same output as in JAVA.

Following is the code written in java

import java.util.Base64;  import java.io.BufferedReader;  import java.io.DataOutputStream;  import java.io.InputStream;  import java.io.InputStreamReader;  import java.net.URL;  import java.net.URLDecoder;  import java.net.URLEncoder;  import java.security.Key;  import java.security.KeyManagementException;  import java.security.NoSuchAlgorithmException;  import java.security.cert.X509Certificate;  import javax.crypto.Cipher;  import javax.crypto.spec.SecretKeySpec;  import javax.net.ssl.HostnameVerifier;  import javax.net.ssl.HttpsURLConnection;  import javax.net.ssl.SSLContext;  import java.util.Arrays;  import javax.net.ssl.SSLSession;  import javax.net.ssl.TrustManager;  import javax.net.ssl.X509TrustManager;    public class HelloWorld {      public static final String PHONENUMBER_PARAM = "phoneNumber";      public static final String PIN_PARAM ="pin";        public static final String MERCHANTID_PARAM = "merchantId";        public static void main(String args[]) throws Exception {        String phoneNumber ="+917738995286";      String pin ="5577";        String merchantId ="527425858";      String encodedKey ="vPDkdTDrcygLPROzd1829A==";        String payLoad = PHONENUMBER_PARAM + "=" +         URLEncoder.encode(phoneNumber, "UTF-8")+ "&" + PIN_PARAM + "=" + URLEncoder.encode(pin, "UTF-8") ;        byte[] decodedKey = Base64.getDecoder().decode(encodedKey.getBytes());        Key encryptionKey = new SecretKeySpec(decodedKey, "AES");        byte[] utf8Bytes = payLoad.getBytes("utf-8");        byte[] encryptedBody = encrypt(encryptionKey, utf8Bytes);      String encryptedData = new  String(Base64.getEncoder().encode(encryptedBody));        System.out.println("encryptedData:" + encryptedData);   }  private static byte[] encrypt(Key encryptionKey, byte[] data) throws Exception {      Cipher c = Cipher.getInstance("AES");      c.init(1, encryptionKey);      return c.doFinal(data);  }  }  

Output of this code is

encryptedData:lE40HlECbxU/mWRivF/+Szm3PprMoLW+Y7x911GczunakbG8l+A2JVEEP8gTw6xy

I tried to write the same code in ruby. Ruby Code is:

payLoad = "phoneNumber=%2B917738995286&pin=5577"    encodedKey = "vPDkdTDrcygLPROzd1829A=="    decodedKey = Base64.decode64(encodedKey)    dKey = decodedKey.each_byte.map { |b| b.to_s(16) }.join    cipher = OpenSSL::Cipher.new('aes128').encrypt  encryptionKey  = cipher.update(dKey)   encryptionKey<< cipher.final      utf8Bytes = payLoad.bytes  uKey = utf8Bytes.map { |b| b.to_s(16) }.join    scipher = OpenSSL::Cipher.new('aes128').encrypt  scipher.key = encryptionKey    encryptedBody = scipher.update(uKey)   encryptedBody<< scipher.final    encryptedData  = Base64.encode64(encryptedBody)  

Output of this code is

CqFmCKJ004PsoXi2tDCTBmx7/iTHVyDsFH9y8NWNrEP3k3bOQp7h8uyl/a7Z\nYi9ZmcXSspo6FCyCo6fJIwPohg==\n

Don't know where is the error. I have already worked for 2 days but not able to get any answer. Any help will be great. Thanks in advance.

ActiveJob with Resque plugins

Posted: 29 Apr 2016 06:10 AM PDT

Is there a way to use Resque plugins, such as resque-loner, with ActiveJob and Resque as backend for it?

Cant use class defined inside lib folder in rails app

Posted: 29 Apr 2016 07:13 AM PDT

I have created a class in my lib folder inside my rails app lib/pundit/current_context.rb :

class CurrentContext    attr_reader :user, :account_asso      def initialize(user, account_asso)      @user = user      @account_asso = account_asso    end  end  

This class is then called in my base_controller :

  def pundit_user      CurrentContext.new(current_user, account_asso)    end  

I am always getting :

NameError - uninitialized constant Api::V1::BaseController::CurrentContext:  

I thought it might be because I am not loading the files inside lib ? so I added config.autoload_paths << Rails.root.join('lib') inside my config/application.rb file :

require File.expand_path('../boot', __FILE__)    require "rails"  # Pick the frameworks you want:  require "active_model/railtie"  require "active_job/railtie"  require "active_record/railtie"  require "action_controller/railtie"  require "action_mailer/railtie"  require "action_view/railtie"  require "sprockets/railtie"  # require "rails/test_unit/railtie"    # Require the gems listed in Gemfile, including any gems  # you've limited to :test, :development, or :production.  Bundler.require(*Rails.groups)    module QuickBedApi    class Application < Rails::Application      # Settings in config/environments/* take precedence over those specified here.      # Application configuration should go into files in config/initializers      # -- all .rb files in that directory are automatically loaded.        # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.      # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.      # config.time_zone = 'Central Time (US & Canada)'        # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.      # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]      # config.i18n.default_locale = :de      config.middleware.insert_before 0, "Rack::Cors" do        allow do          origins '*'          resource '*', :headers => :any, :methods => [:get, :post, :options]        end      end      # Do not swallow errors in after_commit/after_rollback callbacks.      config.active_record.raise_in_transactional_callbacks = true      config.autoload_paths << Rails.root.join('lib')    end    end  

Unfortunately I am still getting the error. How can I solve that ?

Capistrano deployment broken by new request for Capistrano-Harrow gem?

Posted: 29 Apr 2016 06:38 AM PDT

I thought my capistrano version was locked to 3.4.0, however it seems that it updated to 3.5. I tried going back to 3.4, but I keep getting the following message when I try to deploy my project to server.

    DEBUG [72bb6fc3]    An error occurred while installing capistrano-harrow (0.3.2), and Bundler cannot  continue.  Make sure that `gem install capistrano-harrow -v '0.3.2'` succeeds before  bundling.  

I'm not familiar with capistrano-harrow, but read a little and doesn't seem like something I need. I did add to my gemfile in hopes of getting the deployment to send but even though that seemed to install fine, it still errors out for deployment. When I try executing gem install capistrano-harrow -v '0.3.2' - I get the following message and it doesn't install.

ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)      bad response Not Found 404 (https://rubygems.global.ssl.fastly.net/quick/Marshal.4.8/capistrano-harrow-0.3.2.gemspec.rz)  

Anyone know how I can either, opt out of harrow to try and get my deploy to work, or correct this issue to move forward? Thanks!

Update

I ran the following command to "opt-out", however, it still needs to build/install the gem I suppose which is currently the real issue.

git config harrow.disabled true

How to get the records where status is equal to nil and not equal to privilage or casual

Posted: 29 Apr 2016 06:09 AM PDT

i have a leave table. in this i have a status column. which is a string column.i want to get those records from leave table where status column is equal to null and status not equal to privilage or casual or sick. how to write this query in rails 4 ?

leave.where(:status => nil).where.not(:status => "casual" or "privilage" or "sick").  

Rails date check if parsable

Posted: 29 Apr 2016 06:02 AM PDT

I have a datetime picker which sends the checkin & checkout dates with search box. Then the url looks like;

http://localhost:3000/locations/listings?utf8=%E2%9C%93&search=london&start_date=12%2F04%2F16&end_date=20%2F04%2F16  

and I take the params hash and parse the string,

start_date = Date.parse(params[:start_date])  end_date = Date.parse(params[:end_date])  

first of all, I have to check if (start_date.present? && end_date.present?) and that works fine.

But if the user manually types something else rather than the date to url such as;

http://localhost:3000/locations/listings?utf8=%E2%9C%93&search=london&start_date=londoneye6&end_date=20%2F04%2F16   

Then of course I get an error;

invalid date  

How should I control if the string is parsable on controller action. I should be also checking london-eye, london/eye strings, which include - /

Thank you

How can I verify username or email are correct using Devise and Rails 4

Posted: 29 Apr 2016 05:15 AM PDT

I am using Devise and Rails 4.

I am working with login screen. In login screen i'm passing username/email and password but I have to check whether any one of the field username or email matched with any user in system.

Tried following condition to find user with username or email but it will be throwing an error for devise valid password method.

Condition:

user = User.where(["username = :value OR email = :value", { :value => username.downcase }])  

after this i'm checking user password as like user.valid_password?(password)

Error: NoMethodError (undefined method `valid_password?' for #)

For following condition valid_password? will be working fine

user = User.find_by(email: email.downcase)  

But i have to check both username and password in ::find_by method like as follows

user = User.find_by("email= email.downcase OR username= email.downcase")  

Is there some way I can accomplish something like above?

How to convert all daily datat of a year to monthly data

Posted: 29 Apr 2016 05:55 AM PDT

First let me tell you what I want, I want to make a chart of a growth of a users mutual funds portfolio.

Now I have a user who invests in a portfolio last year.

Now I have a task which stores all the daily growth values of a users portfolio in user portfolio growth table.

Now as of current date I have all daily values of a portfolio growth in my user portfolio growth table.

What I want is to show monthly growth of a users portfolio on a graph.

So, my question here is how do I convert all the daily values to monthly values from date of his investment? So, that I can show it on a graph.

UserPortfolio Schema

# == Schema Information  #  # Table name: user_portfolios  #  #  id              :integer          not null, primary key  #  user_id         :integer          not null  #  portfolio_name  :string  #  amount          :integer          not null  #  investment_plan :string           not null  #  duration        :integer          default(1), not null  #  risk_level      :string           not null  #  created_at      :datetime         not null  #  updated_at      :datetime         not null  

UserPortfolioGrowth

# == Schema Information  #  # Table name: user_portfolio_growths  #  #  id                :integer          not null, primary key  #  user_portfolio_id :integer  #  appreciated_value :float  #  created_at        :datetime         not null  #  updated_at        :datetime         not null  #  

Thank You!

Generate array of daily avg values from db table (Rails)

Posted: 29 Apr 2016 04:58 AM PDT

Context: Trying to generating an array with 1 element for each created_at day in db table. Each element is the average of the points (integer) column from records with that created_at day. This will later be graphed to display the avg number of points on each day.

Result: I've been successful in doing this, but it feels like an unnecessary amount of code to generate the desired result.

Code:

def daily_avg      # get all data for current user      records = current_user.rounds        # make array of long dates      long_date_array = records.pluck(:created_at)        # create array to store short dates      short_date_array = []        # remove time of day      long_date_array.each do |date|          short_date_array << date.strftime('%Y%m%d')      end         # remove duplicate dates      short_date_array.uniq!        # array of avg by date      array_of_avg_values = []        # iterate through each day      short_date_array.each do |date|          temp_array = []            # make array of records with this day          records.each do |record|              if date === record.created_at.strftime('%Y%m%d')                  temp_array << record.audio_points              end          end          # calc avg by day and append to array_of_avg_values          array_of_avg_values << temp_array.inject(0.0) { |sum, el| sum + el } / temp_array.size      end      render json: array_of_avg_values  end  

Question: I think this is a common extraction problem needing to be solved by lots of applications, so I'm wondering if there's a known repeatable pattern for solving something like this?

Or a more optimal way to solve this?

(I'm barely a junior developer so any advice you can share would be appreciated!)

How to use order with uniq in a PostgreSQL

Posted: 29 Apr 2016 06:14 AM PDT

How can I use order with uniq?

auction.invoices.get_auction_invoices.item_invoices.  joins("INNER JOIN users ON users.id = invoices.usable_id").order("users.first_name").uniq  

The above query gives me following error:

This is my scopes

scope :item_invoices, ->{ joins(:invoice_details).where("invoice_details.invoiceable_type = ?", "Item")}

scope :get_auction_invoices, ->{where(:id => (item_invoices.skip_cancelled_invoice + donators.skip_cancelled_invoice))}

PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list LINE 1: ...oice_details.invoiceable_type = 'Item') ORDER BY users.firs... : SELECT DISTINCT "invoices".* FROM "invoices" INNER JOIN "invoice_details" ON "invoice_details"."invoice_id" = "invoices"."id" INNER JOIN users ON users.id = invoices.usable_id WHERE "invoices"."eventable_id" = $1 AND "invoices"."eventable_type" = $2 AND "invoices"."id" IN (1132, 1131, 777, 777, 777, 3013, 3024, 3024, 3024, 3024, 3041, 3041, 3013) AND (invoice_details.invoiceable_type = 'Item') ORDER BY users.first_name

rails 4 partial extension required under pdf template

Posted: 29 Apr 2016 04:25 AM PDT

I have using same partial under two different pages. The first one is under simple *.html.haml and the latter under *.pdf.haml.

Example: I have a partial as views/patient/reports/_invoice.html.haml

first Usage:- account.html.haml

= render partial: 'patient/reports/invoice'

second usage:- under invoice.pdf.haml

= render partial: 'patient/reports/invoice.html.haml'

why do I need to provide file extension in the latter one?

Error R13 (Attach error) -> Failed to attach to process on running console on heroku

Posted: 29 Apr 2016 04:05 AM PDT

I want to run rails console on heroku by typing command "heroku run rails console -a getpayad-staging" , but it kept on running and in logs i came up with error "Error R13 (Attach error) -> Failed to attach to process". I have seen couple of answers but not find perfect answer.

ruby on rails rest api with ruby for login page

Posted: 29 Apr 2016 04:22 AM PDT

i want to implement a ruby api for login page with ruby on rails backend in android mobile application, As i am new to this kindly help me to complete my task, and please tell the way to implement an API Thanks in advance

Cannot use password grant_type on 4.0.0 RC3 using Rails 5 Beta

Posted: 29 Apr 2016 03:41 AM PDT

I am trying to use doorkeeper on my Rails 5 app, and want to grant using password grant flow.

Versions used to do this is

  • Rails 5 Beta 4
  • Doorkeeper 4.0.0 RC3

I followed the intstructions here, and when I send a grant_type=password to the /oauth/token, I get an error.

{  "error": "unsupported_grant_type",  "error_description": "The authorization grant type is not supported by the authorization server."  }  

I tried this with a Rails4 app with doorkeeper 3.1.0, and had no problems.

I have created a new app and did the initial setup for doorkeeper, and have used the chrome extension called Advanced REST Client and the curl command to try to send username and password.

Have uploaded sample app on github.

https://github.com/saifis/doortest

How to show entries from the current month?

Posted: 29 Apr 2016 03:44 AM PDT

For the sake of explanation, I'm writing an app where a User can log their expenses.

In the User's show view, I want to only show the User's expenses from the current month.

My expenses table looks like this:

create_table "expenses", force: :cascade do |t|    t.date     "date"    t.string   "name"    t.integer  "cost"    t.datetime "created_at", null: false    t.datetime "updated_at", null: false    t.integer  "user_id"  end  

The date field is in the date format, so looks like: Thu, 14 Apr 2016

In my controller, I've got something like:

def show    month = Date.today.strftime("%m")    @user = User.find(params[:id])    @expenses = Expense.where(:user_id => @user.id, :date => month)  end  

Obviously, this isn't going to work, but it will be something along these lines, I'm guessing?

Any help would be great, thanks!

Ruby issue while configuring sensu checks

Posted: 29 Apr 2016 04:22 AM PDT

I have sensu server and sensu-client Installed on one machine (centos) and installed the the plugins through gem.

Everything was good when I run the check_ping.rb from the command line, but When I configure the same check in /etc/sensu/conf.d/ and check in the UI I am getting this ruby issue;

gem install sensu-plugins-network-checks  

I have ruby installed of 1.9.3 version

and configured EMBEDDED_RUBY=true

when I check the UI the below is the error I am facing

/opt/sensu/embedded/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- net/ping (LoadError)  from /opt/sensu/embedded/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'  from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/sensu-plugins-network-checks-0.2.4/bin/check-ping.rb:31:in `<main>'  Sensu::Plugin::CLI: ["Not implemented! You should override Sensu::Plugin::CLI#run."]  

Can someone help with this?

capistrano excute Makefile fail

Posted: 29 Apr 2016 03:38 AM PDT

I have a problem with excute Makefile

deploy.rb:

namespace :deploy do    after :deploy, :build_app do      on roles(:app), in: :groups do        execute "make production"      end    end  end  

Makefile:

production:      echo "make file production"  staging:      echo "make file staging"  all:      echo "make file all"  

error when run "cap production deploy"

DEBUG [1f0a117d] Command: make production  DEBUG [1f0a117d]    make: *** No rule to make target `production'.  Stop.  (Backtrace restricted to imported tasks)  cap aborted!  SSHKit::Runner::ExecuteError: Exception while executing as make production exit status: 2  make production stdout: make: *** No rule to make target `production'.  Stop.  make production stderr: Nothing written  

Debug run direct on server "make production" => echo "make file production"

And if excute with only "make" it will running to the first tag

--- Makefile addition

production:      npm install      npm run deploy-production      sudo docker rmi dashboard:latest; sudo echo 0      sudo docker build -t dashboard:$(VERSION) .      sudo docker tag -f dashboard:$(VERSION) dashboard:latest    staging:      npm install      npm run deploy-staging      sudo docker rmi dashboard:latest; sudo echo 0      sudo docker build -t dashboard:$(VERSION) .      sudo docker tag -f dashboard:$(VERSION) dashboard:latest  

Unable to establish relationship between two objects in Rspec

Posted: 29 Apr 2016 02:57 AM PDT

I'm writing an RSpec called Leads controller spec. In that I'm writing a test for create action of lead controller. Now my lead controller calls Project model to create an object(Project) which also creates Contact object and assigns it to project. but when I try to test whether my Project model creating a Contact object or no, The tests are getting failed. I don't know why my contact object is not getting created:(

My leads_controller_spec.rb

describe "POST #create" do      it "should create a contact too" do        my_lead = Fabricate(:project, id:  Faker::Number.number(10))        expect{        post :create, project: my_lead.attributes        }.to change(Contact, :count).by(1)      end      it "should be equal to last created contact" do        my_lead = Fabricate(:project, id:  Faker::Number.number(10))        post :create, project: my_lead.attributes        expect(Project.last.contact).to eq(Contact.last)      end    end  

leads_controller.rb

 def create      if @lead = Project.add_new_lead(lead_params)        @lead.create_activity :create_new_lead, owner: current_user        puts "My lead in create action: #{@lead.inspect}"      else        respond_to do |format|          format.html { redirect_to :back, :alert => "Email is already Taken"}        end      end        respond_to do |format|          format.html { redirect_to leads_path }        end     end  

Project.rb

def add_new_lead(inputs, data = {})        if !Contact.where(email: inputs[:email]).present?          contact = Contact.create(phone: inputs[:phone], email: inputs[:email], fullname: inputs[:fullname])          project = Project.create(name: inputs[:fullname], flat_status: inputs[:flat_status], flat_type: inputs[:flat_type], flat_area: inputs[:area], location: inputs[:locality], address: inputs[:site_address], customer_type: inputs[:customer_type])          project.contact = contact          project.save            project          else          return nil        end      end  

contact_fabricator.rb

require 'faker'  Fabricator(:contact) do  email { "email_#{Kernel.rand(1..30000)}@prestotest.com" }  fullname "project#{Kernel.rand(1..30000)}"  address "address#{Kernel.rand(1..30000)}"    end  

project_fabricator.rb

require 'faker'  Fabricator(:project) do        contact  end  

contact.rb

  field :phone,             type: String               field :email,             type: String    field :fullname,          type: String    field :status,            type: String,       default: "DEFAULT"    field :address,               type: String    field :new_address,       type: String    field :other_data,        type: Hash,         default: {}       validates_presence_of :email    validates_uniqueness_of :email, :message => "Email already taken"  

Unable to download .docx file using Capybara in ruby [duplicate]

Posted: 29 Apr 2016 02:56 AM PDT

This question is an exact duplicate of:

I am trying to download the .docs file by using capybara in ruby but all file is getting download except .docx. so plz tell me how can i download the .docx file using ruby

profile = Selenium::WebDriver::Firefox::Profile.new profile['browser.download.dir'] = '/tmp/' profile['browser.download.folderList'] = 2 profile['browser.helperApps.neverAsk.saveToDisk']="images/jpeg,application/pdf, application/doc, application/docx, text/csv, application/octet-stream"

profile['pdfjs.disabled'] = true profile.native_events = true @driver = Selenium::WebDriver.for :firefox, profile: profile puts '===============> Download will start now ===================>' @driver.get link puts '===============> Download is over ===================>'

belongs_to with different foreign key as well as primary key in the other table

Posted: 29 Apr 2016 02:56 AM PDT

I have two models:

Ticket and User

A ticket belongs_to a User, and a User has_many Tickets.

The thing here is that I want to associate these two models with:

The ticket has a ref_token column and the User has a token column. So, basically when trying to find the User for a given token (token123), I would expect the following query:

SELECT * FROM tickets WHERE token = 'token123'  

How can I set the association to accomplish this (basically I want to specify the columns that set the association. In this case they are different than the primary keys).

I have this now:

User    has_many :tickets, foreign_key: 'ref_token', primary_key: 'token'    Ticket    belongs_to :user, foreign_key: 'ref_token', primary_key: 'token'  

And I am able to do user.tickets, but I can't do ticket.user. It keeps returning nil.

Create a auth user using devise

Posted: 29 Apr 2016 03:58 AM PDT

Im using devise in my rails application and everything is working fine, what Im trying to do now is to allow users to login to my app using their github account and create a profile.

User.rb

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable, :omniauthable      has_one :profile      after_create :build_profile      def build_profile      self.create_profile    end      def self.create_with_omniauth(auth)      user = first_or_create do |user|        user.provider = auth['provider']        user.uid = auth['uid']        user.email = auth['info']['email']        user.password = Devise.friendly_token[0,20]      end    end  end  

routes.rb

devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }  

callbacks_controller.rb

class CallbacksController < Devise::OmniauthCallbacksController    def github      @user = User.from_omniauth(request.env["omniauth.auth"])      sign_in_and_redirect @user    end  end  

I also ran the correct migration to add provider and uid column to the users table

rails g migration AddColumnsToUsers provider uid    def change   add_column :users, :provider, :string   add_column :users, :uid, :string  end  

config/initializers/devise.rb

config.omniauth :github, 'CLIENT_ID', 'APP_SECRET', :scope => 'user:email'  

When i create a user using devise it all works fine and users are created, but when i click sign in with github on my registration page it merges the devise account and github account together leaving me with one account, its not creating an account with user github credentials. Even if i try and login using 2 different github accounts, it still for some reason only uses the first github account.

problem is github user can login but they are not being created as users, using their github credentials, i need users to login and create a profile with me.

Elasticearch result only on the basis of Term Frequency,avoiding Inverse document frequency and Field-length norm

Posted: 29 Apr 2016 06:47 AM PDT

I am using Elasticsearch version 2.3.1 for the search along with Ruby On Rails . I am using query_string for the search . It calculates the score on the basis of three factors :- 1.Term Frequency 2.Inverse document frequency 3.Field-length norm

I just want Term Frequency to be used for calculating score . Any way by which i could disable Inverse document frequency and Field-length norm factor in calculating score .

After some R&D on the topic i came with constant_score query which indirectly gives weightage to Term Frequency .

The problem which I know facing is that : e.g If i search for "good street food" it treats document having only "good" ,or "good food", or completely "good street food" with same score . But I want document with "good street food" should have higher score than "good food" , "good food" score higher than "good" .

The One solution which I came across is :

word_search1.each do |word_search|                          @search_definition[:query][:bool][:should] << {                constant_score:{query:{query_string:{                fields: ["group_name"] ,                query:word_search                }}}}                @search_definition[:query][:bool][:should] << {                constant_score:{query:{query_string:{                fields: ["message"] ,                query: word_search                }}}}                @search_definition[:query][:bool][:should] << {                constant_score:{query:{query_string:{                fields: ["tag_name"] ,                query: word_search                }}}}                @search_definition[:query][:bool][:should] << {                constant_score:{query:{query_string:{                fields: ["name"] ,                query: word_search                }}}}     end    Here word_search1=["good","street","food"]  

This some how solve my problem as know i am treating every word as different query rather than full string . But If someone has any better and optimize solution than this in which i could enter entire string in one line rather than loop and it gives priority to that document which has best matching or contains some word multiple times would love to know about that solution.

.docx file is not downloading with capybara

Posted: 29 Apr 2016 04:34 AM PDT

I am trying to download the .docs file by using capybara in ruby but all file is getting download except .docx. so plz tell me how can i download the .docx file using ruby

profile = Selenium::WebDriver::Firefox::Profile.new  profile['browser.download.dir'] = '/tmp/'  profile['browser.download.folderList'] = 2  profile['browser.helperApps.neverAsk.saveToDisk'] = "images/jpeg, application/pdf, application/doc, application/docx, text/csv, application/octet-stream"       profile['pdfjs.disabled'] = true   profile.native_events = true  @driver = Selenium::WebDriver.for :firefox, profile: profile   puts '===============> Download will start now ===================>'  @driver.get link   puts '===============> Download is over ===================>'  

Comparing values of Ruby XMLRPC datetime returned from API to normal Ruby DateTime object

Posted: 29 Apr 2016 02:51 AM PDT

I have an XMLRPC datetime returned from a remote API, and I want to perform normal comparison operations to a standard Ruby datetime object, such as >, <, >=, etc. I've read that XMLRPC has some strange datetime restrictions (such as it doesn't support values before or after a certain date) and using DateTime.parse() for the returned object doesn't work, with or without string interpolation.

How do you accurately convert an XMLRPC::DateTime object to a standard Ruby 2.2.2 DateTime object so I can execute comparisons, regardless of the date returned?

Localized dropdown with all month names

Posted: 29 Apr 2016 05:34 AM PDT

I am trying to make in Rails 4 a dropdown with all the months. I do it like this:

<select >      <% (1..12).each do |month| %>          <option value="<%= month %>"><%= Date::MONTHNAMES[month] %></option>      <% end %>  </select>  

The problem now is that I would like to localize it, but I can't apply the locate method on simple Strings with the names of the months.

How could I solve this?

Update

I know I can translate them myself, but I was hoping, since Rails is so kind to give me the names in English, if there was any way that Rails could give it to me in other languages as well.