mercredi 31 mai 2017

Rails: A method with no definition?

I am reading a Rails code not written by me. I am trying to understand the purpose of some method, but I can't find its definition anywhere in the source code. The method is called on_init. I have searched for matches for the string def on_init with no results.

Does anyone has an idea how can I find out the purpose of this method?

Thank you in advance!

String comparison: I dont understand the failure

I have 2 arrays with the same content.

But the first string has a size of 6 and the second string has a size of 5.

How can I comparise these two strings and get a positive return? Both strings has the same content, but when I comparise that, i get false as return.

if str1 == str2
###
end

Ruby on Rails: Anything selected with 'joins' is readonly

So we're having some difficulty with the readonly? method in activerecord classes. It appears that anything fetched with a call to joins is being set to readonly and throws this error

ActiveRecord::ReadOnlyRecord: ActiveRecord::ReadOnlyRecord

For instance:

# fine 
User.first.readonly?
User.first.save
# not fine
User.joins(:memberships).first.readonly?
# false
User.joins(:memberships).first.save
# ActiveRecord::ReadOnlyRecord

According to the Rails documentation this will be set to false for "Records loaded through joins with piggy-back attributes."

As far as I'm aware, we're not including any piggy-back attributes here.

I can forcibly circumvent this restriction, but it feels like I'm hacking through the system unnecessarily.

user = User.joins(:memberships).first
User.instance_variable_set(:@readonly, false)
user.save

Does anyone know why joins is returning readonly items? Can I prevent this? (I'm not trying to select any attributes from related objects).

I'm using Ruby on Rails version 3.2.22.5, It looks like this has been a change in behavior from an earlier version of Rails 3.

How can I build array dynamically for 21 fields per element?

I want to build an array dynamically for 21 fields per element. Everything must be done in the view.

How can I do that?

Every element must have 21 fields and I have to access it later like

@xyz.each do |element|
  puts element["fieldA"]
end

Rails 3 Can't update record in DB

Hello I have model Types with 2 fields: photo and name. I can create new record but can't update it. Why? Operations is very similiar. Here's creating new record it's working. Controller

def new_type
 @type = Type.new(params[:type])
if @type.save
  redirect_to types_path
else
  render 'create_type'
end end

HTML file

<%= form_for @type, :url => { :action => "new_type" }, :html => { :multipart => true } do |f| %> <% end %>

<%= f.label :NAME %><br/>
<%= f.text_field :name %><br/>
<%= f.label :photo, "Your photo" %><br/>
<%= f.file_field :photo %><br />

<%= f.submit "ADD"%>  <% end %>

And Updating (not working)

def edit_type
 @type = Type.find(params[:id])
 end

def update_type
     @type = Type.find(params[:id])

if @type.update_attributes(params[:type])
  redirect_to types_path
else
  render 'edit_type'
end end

View with all my types

<% for t in @ts %>
<p> <%= t.name %></p>
<%= image_tag t.photo.url(:small) %><br/>
<%= link_to "EDIT", {:controller => "users", :action => "edit_type", :id => "#{t.id}" } %>

Edit VIEW

<%= form_for @type, :url => { :action => "edit_type", :id => "#{@type.id}" }, :html => { :multipart => true } do |f| %>

    <%= f.label :NAME %><br/>
    <%= f.text_field :name %><br/>
    <%= f.label :photo, "PHOTO" %><br/>
    <%= f.file_field :photo %><br />

    <%= f.submit "UPDATE"%>

<% end %>

create new crud in rails application using activeadmin

i am new in ROR. and install an gem for admin dashboard named as activeadmin, but now i want to create more curd in that admin gem . i cannnot use scafold because it will create functions in app folder.

please guide me the better approche

mardi 30 mai 2017

Unable to connect to database from rails console on dockers

I have my rails project setup on Digitalocean using Dockers. This is my docker-compose.prod.yml file.

version: "2"

volumes:
 db-data:
   external: false

services:
 db:
  image: postgres
  env_file: .env.production
 volumes:
   - db-data:/var/lib/postgresql/data

app:
 build: .
 env_file: .env
 environment:
   RAILS_ENV: production
 ports:
   - "3000:3000"
 depends_on:
   - db

and this is my database.yml file

default: &default
 adapter: postgresql
 encoding: unicode
 host: db
 username: <%= ENV["POSTGRES_USER"] %>
 password: <%= ENV["POSTGRES_PASSWORD"] %>
 # For details on connection pooling, see rails configuration guide
 # http://ift.tt/1k2jGKr
 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
 <<: *default
 database:  project_development

test:
 <<: *default
 database: project_test

production:
 <<: *default
 host: <%= ENV["POSTGRES_HOST"] %>
 database: project_production

I have created two docker images. One for app and one for postgres/db.

My application is working fine on production. I am able to create and delete records from my web page on production.

But, when I try to access rails console of production database from docker bash by following commands:

docker run -i -t project_app:latest bash 

to access console:

RAILS_ENV=production rails c

Inside Rails Console whenever I try to access any model data or try to perform any query(i.e Model.first etc) I am unable to access postgres database. It shows me following error:

PG::ConnectionBad: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

I have tried many possible solutions to resolve this issue but unable to resolve this.

Please help me! Thanks in advance

Best practice for Rails setup w/ Docker on a Windows machine

I am brand new to Rails and Docker, and am looking to develop a website that runs on Rails and deploys to Production with the help of Docker (likely to AWS).

What would be best practice for setting up my development environment considering I am on a Windows machine?

ADDENDUM:

I understand there are many problems running Rails on Windows, two known solutions for which are:

  1. Spin up a Unix VM (VirtualBox, Vagrant) on my Windows machine and install Ruby / Docker / my favorite IDE onto it. Develop from there.
  2. Use Docker to circumvent the need for a Virtual Machine.

I guess I am confused about this last point. From my limited understanding of Docker, I know that I can use it to create an image of my local app and launch containers of it anywhere. BUT, aren't I still doing my development on Windows? (and hence still subject to all of the known problems with Rails-Windows installations).

Maybe I am missing something about this solution, like somehow running Rails off of a Unix image on Docker or something. Does any of this make sense? Advice would be much appreciated.

Thank you in advance!

lundi 29 mai 2017

How to change the url for Home and Dashboard buttons in Rails admin?

Is there any configuration to change the default URL for home and dashboard buttons in rails admin ?

How to set up error messages of associated model?

Hello rails community!

I have booking_post model that has_many reservations.

class BookingPost < ApplicationRecord
    has_many :reservations, dependent: :destroy
end

All reservation belongs_to booking_post and have some validations

class Reservation < ApplicationRecord
    belongs_to :booking_post
    before_save { self.email = email.downcase }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX }
    validates :name, :email, :phone_number, :start, :end, presence: true
end

My routes are next:

resources :booking_posts do
  resources :reservations, only: [:new, :create]
end

Methods:

class BookingPostsController < ApplicationController
  def show
    @booking_picture = @booking_post.booking_pictures.build
    @booking_pictures = @booking_post.booking_pictures
    @reservation = @booking_post.reservations.build
    @reservations = @booking_post.reservations
  end
end


class ReservationsController < ApplicationController
  def new
    @reservation = Reservation.new
  end
  def create
    @booking_post = BookingPost.find(params[:booking_post_id])
    @email= User.where(admin: true).first.email
    @reservation = @booking_post.reservations.build(reservation_params)
      if @reservation.save
        @saved_reservation = @reservation
        redirect_to :back 
        flash[:notice] = 'Reservation was successfully created.'
        ReservationMailer.fresh_message(@saved_reservation, @email).deliver_now
      else
        redirect_to @booking_post
        flash[:info] = @reservation.errors.full_messages do |m|
          m
        end
      end
  end
end

I would like to create on booking_posts/show.html.erb form_for @reservation, and render on this page errors for @reservation. When I create valid @reservation, I see on booking_posts/show.html.erb successfull flash message, but unvalid @reservation appear without any error flash messages.

form_for @reservation on booking_posts/show.html.erb:

<div class="card-action">
  <%= form_for([@reservation.booking_post, @reservation], html: {multipart: true}, class: "col s12") do |f| %>
  <% if @reservation.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@reservation.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @reservation.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="col s6">
    <%= f.label :start %>
    <%= f.date_field :start, placeholder: "start time",  class: "datepicker" %>
  </div>
  <div class="col s6">
    <%= f.label :end %>
    <%= f.date_field :end, placeholder: "end time",  class: "datepicker" %>
  </div>
  <div class="col s6">
    <%= f.label :reservation_time %>
    <%= f.time_field :reservation_time, placeholder: "time", class: "timepicker", id: "timepicker", type: "time" %>
  </div>

  <div class="input-field col s6">
    <%= f.label :name %>
    <%= f.text_field :name, class: "validate" %>
  </div>
  <div class="input-field col s6">
    <%= f.label :email %>
    <%= f.text_field :email, class: "validate" %>
  </div>
  <div class="input-field col s6">
    <%= f.label :phone_number %>
    <%= f.text_field :phone_number, class: "validate" %>
  </div>

  <div class="waves-effect waves-light btn">
    <%= f.submit t(:submit_reservation)%>
  </div>  

<% end %>
<br>
</div>

I would like render error messages for @reservation on @booking_post page (in booking_post_path, not in new_reservation_path or anyting else). How can I do so?

Thanks for solutions

dimanche 28 mai 2017

how to Redirect a page on successful sign in rails devise and after verify user== "teachers"

redirect to a specific page on the successful sign in. anyone can advise me how to redirect an after verify (userid == teacher ).if userid is a teacher then redirect teacher otherwise student page pbl01/config/routes.rb

Rails.application.routes.draw do
devise_for :users, :controllers => {
:registrations => 'users/registrations'
}
resources :import,only: [:index,:create]
root 'root#index'

# For details on the DSL available within this file, see 
http://ift.tt/GVpneB
end

pbl01/app/controllers/users/sessions_controller.rb

class Users::SessionsController < Devise::SessionsController

def new

end

def create
@user = User.new(user_params)
if @user.save
@userid = User.find_by(userid:params[:userid])
if @userid.userid == 'teacher'
  redirect_to root_path
else
 redirect_to timesset_path

end
else
  flash[:notice] = "Invalid Username or Password"
  flash[:color]= "invalid"
  render "new"  
   end

end

pbl01/app/models/user.rb

require 'csv'
class User < ApplicationRecord
validates :userid, :presence => true,
validates :password, :presence => true,


devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

def email_required?
false
end
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|

  users = find_by(userid: row["userid"]) || new

  users.attributes = row.to_hash.slice(*updatable_attributes)
  users.password= row["password"]

  users.save!
end
end


def self.updatable_attributes
["userid", "name", "email"]
 end
end

pbl01/app/views/devise/sessions/new.html.erb

<h2>Log in</h2>

<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
 <% if @user.errors.any? %>
<div class="field">
<%= f.label :userid %><br />
<%= f.text_field :userid, autofocus: true %>
</div>

<div class="field">
<%= f.label :password %><br />
<%= f.password_field :password, autocomplete: "off" %>
<% for message_error in @user.errors.full_messages %>
  <li>* <%= message_error %></li>
<% end %>
</div>

<% if devise_mapping.rememberable? -%>
<div class="field">
  <%= f.check_box :remember_me %>
  <%= f.label :remember_me %>
</div>
<% end -%>

<div class="actions">
 <%= f.submit "Log in" %>
 </div>
 <% end %>

 <%= render "devise/shared/links" %>

How to Rails keep with domain name on the links?

After Bought a ssl certification and added to the server some links like the log

in session that i click when redirect show the sever ip instead and cause the ssl

connection not secure problem, so, how to make rails links not cause this kind of problem?

Unable to SSH into DigitalOcean droplet which wad created by "docker-machine" command

I have created a DigitalOcean droplet using docker-machine command. Now, I am unable to login from my local machine to droplet because my ssh key is not added to server. I have used the following command to create droplet

docker-machine create --driver=digitalocean --digitalocean-access-token=MyToken --digitalocean-size=1gb  --digitalocean-backups=true --digitalocean-ssh-user=root myapp

I created the droplet from my local machine. I have added my local access key to droplet as well but I am still unable to login.

I am using the following command to ssh

ssh root@droplet-ip-address

I have tried to access droplet from digitalocean console as well but it does not allowed me to copy/paste ssh key.

Is there any other way to solve this issue? Please help me

Rails Repo pointing to old gem version

I am using rails engine as gem in my application, but after deploying through capistrano on server and even after bundling the latest gem version repo always points to old gem version.

This is my Gemfile

gem 'crowd',git: 'git@bitbucket.org:prem/boold-crowd.git', branch: 'dev', ref: 'baa893230325f5aceffd0b0c4b471cd145644c8e'

I have pointed my repo to dev branch and commit version baa893230325f5aceffd0b0c4b471cd145644c8e but when checking the gem version in bundler folder in

/home/deploy/boold/shared/bundle/ruby/2.2.0/bundler/gems/

I can see their are 2 gems with two versions one new version and one old version and my repo always points to older version even after fresh deployment.

boold-crowd-d759cbaf83ea  #this is the older gem version where app is pointed
boold-crowd-baa893230325  #new version which never gets used.

raise RestClient::ServerBrokeConnection rails error

when My request return hug json as a result rest-client return error:

raise RestClient::ServerBrokeConnection

but smaller json result works well

samedi 27 mai 2017

Has_one through AND has_many through together

Hello i have 3 models:

  • Sale
  • Customer
  • Customer Address

-Each SALE should have only one CUSTOMER

-Each CUSTOMER can have more than one SALE

That works great, there's no problem here, but now i need something like this:

-Each SALE should have only one CUSTOMER_ADDRESS

-Each CUSTOMER can have more than one CUSTOMER_ADDRESS


And then, how can i do this?

Can i use has_one through and has_many through together?

vendredi 26 mai 2017

How to copy a attribute of another model in rails?

i'm trying yo get the email from user after create but in the logs show a error

the method that i'm trying is:

someone can spare a hint?

class Car < ActiveRecord::Base

belongs_to :user

after_create :get_email

def get_email
   email = user.email.dup

  end
end

Rails send 2 emails in one mailer function

I'm trying to send 2 emails on the same function but after send the log show

An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address

if i remove one email works, and everything is configured ok.

someone can know about this issue?

def dispute_confirmation(dispute)
    @dispute = dispute


    mail(to: @dispute.buyer_email, subject: 'Reclamação Aberta', &:html)

     mail(to: @dispute.seller.email, subject: 'Comprador abriu uma Reclamação', &:html)


  end

Setting path of imagemagik

I installed imagemagik in the past and was working fine until i reinstalled rails, imagemagik is still installed but when i try to type which convert to get the path of /usr/local/bin/ i get this error on the command line. My question is how do i fix the path so that when i type which convert it reads /usr/local/bin/. Or do i have to reinstall imagemagik which can be a pain at times

command line

'which' is not recognized as an internal or external command,
operable program or batch file.

rails server

Command :: SET PATH=/usr/local/bin/;%PATH% & file -b --mime "C:/Users/Michael/AppData/Local/Temp/5664a0e0a6a4bd4baf3d5e2cecfcad5520170526-26284-1n2fgrk.jpg"
[paperclip] Content Type Spoof: Filename Mario_(Mario_Kart_Wii).jpg (image/jpeg from Headers, ["image/jpeg"] from Extension), content type discovered from file command: . See documentation to allow this combination.
   (0.0ms)  begin transaction
Command :: SET PATH=/usr/local/bin/;%PATH% & file -b --mime "C:/Users/Michael/AppData/Local/Temp/5664a0e0a6a4bd4baf3d5e2cecfcad5520170526-26284-1w5guoi.jpg"
[paperclip] Content Type Spoof: Filename Mario_(Mario_Kart_Wii).jpg (image/jpeg from Headers, ["image/jpeg"] from Extension), content type discovered from file command: . See documentation to allow this combination.

Rails detect if object is session table

I use rails 3.2. I try to add a global check on a field of my model called account_id. My problem is that there are tables that not have this field like sessions table and others. So I have my object self and I use if condition like

if self.name.to_s!="Base" and self.name!="Session"

but the session object passed the if condition, below the error

PG::UndefinedColumn: ERROR: column sessions.account_id does not exist

How I can detect if self is session object? I see that in other case self in my function is for example NamTable+attributes ex Base[id:ecc]

How to check if schema exists in Ruby on Rails migration

I'm using Rails 5.0.2, Postgresql as database and Heroku Connect to syncronize data with salesforce.

I've already had the public schema when are created the tables of the application but Heroku Connect writes on the same database salesforce's tables. I need to add a field in a table of salesforce schema.

I've found the method schema_exists? (http://ift.tt/2r4kxXu) but i don't know how to implement it, i'm new on RoR.

This is my migration code:

class CreateSchema < ActiveRecord::Migration[5.0]
      def change
    if !schema_exists?('salesforce')
      execute "CREATE SCHEMA salesforce"
    end
    if !table_exists?('salesforce.ontap__order__c')
      create_table 'salesforce.ontap__order__c'
    end
    add_column :'salesforce.ontap__order__c', :currencyisomode, :string
    if !table_exists?('salesforce.ontap__order_item__c')
      create_table 'salesforce.ontap__order_item__c'
    end
    add_column :'salesforce.ontap__order_item__c', :currencyisomode, :string
  end
end

What i'm doing wrong?

What is :manage, :all doing in Ruby?

I have a basic authorization class in a Rails application which looks like this:

class Ability
  include CanCan::Ability

  def initialize(user)

   if user
     can :access, :rails_admin       # only allow admin users to access Rails Admin
     can :dashboard
     if user.admin?
       can :manage, :all
     else
       can :manage, [Agreement, Attachment, Contact, Deadline, Event, Image, Photo, Project, Submission, Talk]
       can :update, User, id: user.id
     end
   end

   # Current user cannot delete his account
   cannot :destroy, User, id: user.id
  end
end

Now, I get an unauthorized error when trying to access the dashboard with a simple user, but once I put can :manage, :all for a simple user condition it is misteriouslly let through and see the dashboard.

What is :manage, :all having more than :manage, [All_my_tables] and why is my user not let in using this way?

How to sanitize input in rails .erb file

I am new to ruby on rails.

I have a .erb file with HTML contents.

<input type="text" name="username" placeholder="enter your username" id="user" value="<%= params["username"] %>" />

my HTML page accepts an input and when I give it any random input: <img src=x onerror=prompt(1)> it will causes Cross-site Scripting vulnerability.

Please suggest how to fix this issue. i do some googling and find html_escape is one option, please suggest how to use it in erb files.

jeudi 25 mai 2017

AASM does not trigger before callbacks on calling the same state/event again

I have following state machine - which is NOT sending the mails again after I called the send_mail method once. It works only the first time?!

aasm do
  state :created, initial: true
  state :mail_sent do
    before do
      Mailer.send_mail().deliver
    end
  end

  event :send_mail do
    transitions from: [:created, :mail_sent], to: :mail_sent
  end
end

How is the best practice to do this?

Spliting ruby string with double quotes

I have a string like this-

:customer_key=>"Auto_2505114328103264"

I want to extract the string to Auto_2505114328103264

I tried- (customer_key.to_s).split("") and (customer_key.to_s).split(" " " ")

but this is not working. What am I doing wrong?

Rails overide default scope global

I have a Rails 3.2 application, and I want to use one database for many clients and one application. So for every model I have created a field called account_id, now I want to add a global scope for filtering the row in base of the account_id of the logging user(account_id is a session params). So in initialize I have created a file and put these code

module ActiveRecord
  # = Active Record Named \Scopes                                                                                                                                                                                 \

  module Scoping
    module Default
      module ClassMethods

        def unscoped #:nodoc:                                                                                                                                                         
            return  (block_given? ? relation.scoping { yield } : relation).where(account_id: Thread.current['account_id'].id)

    end

        def default_scope(scope = {})
          scope = Proc.new if block_given?
          if scope.kind_of?(Array) || scope.is_a?(Hash)
              scope.merge!({:conditions=>{account_id:Thread.current['account_id'].id}})
            end
            self.default_scopes = default_scopes + [scope]
          end
        end
   end
  end
end

If I logged with user account_id=2 all is ok, but if in the same moment I logged on another browser or computer with account_id=3 ...I have many errors and on the log I have seen that the application use account_id=2 but also account_id=3 at the same time.......Any solution? How I can Rewrite default_scope(scope = {}) ? Other idea

mercredi 24 mai 2017

Rails undefined method `update_attributes' for false:FalseClass

If the dispute save the change the order boolean false to true but after create the rails log show

undefined method `update_attributes' for false:FalseClass

Someone know why?

order 
has_one :dispute

dispute
belongs_to :order


def create
    if   current_user == @order.buyer



      dispute = @order.dispute.nil? ? Dispute.new : @order.dispute

      if dispute.save
@order = params[:dispute_status] == "1"

         @order.update_attributes(:dispute_status => true

        redirect_to order_dispute_path(@order, @dispute)
        flash[:success] = 'yess'

      else
        flash[:error] = 'Erro'
        redirect_to :back
      end
    end
  end

RubyOnRails - Cannot generate new controller

I'm very new to rails and in fact this is my first blog application that I am working on. I am not able to generate a new controller as my terminal throws me

/Users/dilloncoffman/.rvm/gems/ruby-2.4.1/gems/railties-5.0.3/lib/rails/railtie/configuration.rb:95:in `method_missing': undefined method `load_defaults' for #<Rails::Application::Configuration:0x007ff653d37830> (NoMethodError)
from /Users/dilloncoffman/desktop/blog/config/application.rb:12:in `<class:Application>'
from /Users/dilloncoffman/desktop/blog/config/application.rb:10:in `<module:Blog>'
from /Users/dilloncoffman/desktop/blog/config/application.rb:9:in `<top (required)>'
from /Users/dilloncoffman/.rvm/gems/ruby-2.4.1/gems/railties-5.0.3/lib/rails/commands/commands_tasks.rb:156:in `require'
from /Users/dilloncoffman/.rvm/gems/ruby-2.4.1/gems/railties-5.0.3/lib/rails/commands/commands_tasks.rb:156:in `require_application_and_environment!'
from /Users/dilloncoffman/.rvm/gems/ruby-2.4.1/gems/railties-5.0.3/lib/rails/commands/commands_tasks.rb:143:in `generate_or_destroy'
from /Users/dilloncoffman/.rvm/gems/ruby-2.4.1/gems/railties-5.0.3/lib/rails/commands/commands_tasks.rb:60:in `generate'
from /Users/dilloncoffman/.rvm/gems/ruby-2.4.1/gems/railties-5.0.3/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
from /Users/dilloncoffman/.rvm/gems/ruby-2.4.1/gems/railties-5.0.3/lib/rails/commands.rb:18:in `<top (required)>'
from /Users/dilloncoffman/desktop/blog/bin/rails:4:in `require'
from /Users/dilloncoffman/desktop/blog/bin/rails:4:in `<main>'

I've looked at various articles and those that have had a similar problem starting out for the past two hours. I've tried bundle update and bundle install, however nothing is working. I am trying to implement the gem mail_form into my application but ran into this error after getting installed and trying to generate a new controller for a contacts page. Any help is greatly appreciated!

need help to fix this Can't verify CSRF token authenticity

Can't verify CSRF token authenticity. Redirected to http://localhost:3000/ Completed 302 Found in 1ms (ActiveRecord: 0.0ms)

Trying to make associations with Rails

i'm learning Rails and i'm doing an exercise to practice associations and migration files.

Currently, trying to make a models between users, auction item, and bids.

So far for the migrate files I have the following:

    class CreateItem < ActiveRecord::Migration
      def change
        create_table :auction do |t|
            t.string :item_name
            t.string :condition
            t.date :start_date
            t.date :end_date
            t.text :description

      t.timestamps
    end
  end
end


 class CreateBids < ActiveRecord::Migration
  def change
    create_table :bids do |t|
      t.integer :user_id
      t.integer :auction_id

      t.timestamps
    end
 end
end


   class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :email
      t.string :username
      t.string :password_digest

      t.timestamps
    end
  end

end

These are the following models:

class Bid < ActiveRecord::Base
  belongs_to :bidder, class_name: "User", foreign_key: "bidder_id"
  belongs_to :auction
end


class User < ActiveRecord::Base
  has_many :bids
  has_many :auctions, :foreign_key => 'bidder_id'

  has_secure_password
end


class Auction < ActiveRecord::Base
  belongs_to :seller, class_name: "User", foreign_key: :user_id
  has_many :bids
  has_many :bidders, through: :bids
end

Any suggestions or opinions? I'm currently trying to test the tables but auctions doesn't seem to be working... Specifically, my auction table can't seem to find a user_id and therefore a user doesn't have any auctions.

Rails3 How put my arrai into f.select [duplicate]

This question already has an answer here:

I have an array with categories. How to put elements of array into dropdown list?

<% array = ["W", "H", ..]%>
<%= f.select :type, ['Work', 'Home', 'Other'],  :prompt => 'Select type' %>

AASM state machine exception handling example?

I'm currently working on a class, which is basically doing following:

  • model gets created
  • fetches data (event "get_things!")
    • if exception happens, state should become "failed"
    • if success, state should be "finished"

I try to implement it as following:

class Fetcher < ActiveRecord::Base
  include AASM

  aasm do
    state :created, initial: true
    state :success, :failed

    event :succeed do
      transitions from: :created, to: :success
    end

    event :fail do
      transitions from: :created, to: :failed
    end
  end

  def read_things(throw_exception = false)
    begin
      raise RuntimeError.new("RAISED EXCEPTION") if throw_exception
      self.content = open("http://ift.tt/2qVwIFK").read
      self.succeed!
    rescue => e
      self.fail!
    end
  end
end

a = Fetcher.new
a.fetch!(throw_exception = true)

a = Fetcher.new
a.fetch!(throw_exception = false)

It works, but looks somehow not really good to do...

I would prefer something like the error handling which is mentioned in the readme

event :read_things do
  before do
    self.content = open("http://ift.tt/2qVwIFK").read
    self.succeed!
  end
  error do |e|
    self.fail!
  end
  transitions :from => :created, :to => :success
end

but I dont know if this is really the best practice here?

Any thoughts? Thanks!

Getting Nil for the ip address

I am using geocoder gem to fetch the ip address of the user(while they logging-in), till a month before it works well. but, now it is not working , can anybody help to overcome this issue. thanks in advance.

2.3.0/gems/twitter-6.1.0/lib/twitter/rest/response/raise_error.rb:13:in `on_complete': Bad Authentication data. (Twitter::Error::BadRequest)

Simply put, I'm attempting to post a tweet using these pieces of ruby code:

require 'Twitter'

client = Twitter::REST::Client.new do |config|
config.consumer_key        = "my_key"
config.consumer_secret     = "my_secret_key"
config.access_token        = "my_token"
config.access_token_secret = "my_secret_token"
end

client.update("I'm tweeting with a @gem!")

I'm using 64-bit ruby 2.3.0 with the appropriate 64-bit dev kit on Windows 10.

However, a `on_complete': Bad Authentication data. (Twitter::Error::BadRequest) appears like so:

C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/twitter-6.1.0/lib/twitter /rest/response/raise_error.rb:13:in on_complete': Bad Authentication data. (Twitter::Error::BadRequest) from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/faraday-0.11.0/lib/faraday/response.rb:9:inblock in call' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/faraday-0.11.0/lib/faraday/response.rb:61:in on_complete' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/faraday-0.11.0/lib/faraday/response.rb:8:incall' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/faraday-0.11.0/lib/faraday/request/url_encoded.rb:15:in call' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/faraday-0.11.0/lib/faraday/request/multipart.rb:14:incall' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/twitter-6.1.0/lib/twitter/rest/request/multipart_with_file.rb:21:in call' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/faraday-0.11.0/lib/faraday/rack_builder.rb:139:inbuild_response' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/faraday-0.11.0/lib/faraday/connection.rb:377:in run_request' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/faraday-0.11.0/lib/faraday/connection.rb:177:inpost' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/twitter-6.1.0/lib/twitter/rest/request.rb:33:in perform' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/twitter-6.1.0/lib/twitter/rest/utils.rb:50:inperform_request' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/twitter-6.1.0/lib/twitter/rest/utils.rb:72:in perform_request_with_object' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/twitter-6.1.0/lib/twitter/rest/utils.rb:64:inperform_post_with_object' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/twitter-6.1.0/lib/twitter/rest/tweets.rb:158:in update!' from C:/tools/ruby23/lib/ruby/gems/2.3.0/gems/twitter-6.1.0/lib /twitter/rest/tweets.rb:128:inupdate' from om_tweet.rb:11:in `'

Thanks in advance for your time and advice!

mardi 23 mai 2017

Rails how to straight 3 row conditional?

I'm trying to direct the user to option 3 if option 1 or 2 are not used so i did: but when i check the page shows:

syntax error, unexpected keyword_ensure, expecting keyword_end

someone know why this syntax error?

   <%if order.dispute.status == "open" %>

        <li>  <%= button_to 'Dispute Open',  order_dispute_path(order), method: :get, class: 'btn_grey' %>
      </li>

    <% elsif %>
    <li>
    <%= button_to 'Dispute',  new_order_dispute_path(order), method: :get, class: 'btn_grey' %>


      </li>

    <% else %>
      <li>

        <%= button_to 'Dispute closed',  closed_order_dispute_path, method: :get, class: 'btn_grey' %>

      </li>

    <% end %>

Rails Devise: two different after_update_path_for

I have two pages rendering the update user form of Devise. The classic one (users/edit) and a '/page' page with just a part of the full edit form. I would like to have two different after_update_path whether the form is submit to one or the other page. I tried several things but I none are working...

def after_update_path_for(resource)
    if current_page?('/page')
      :page
    else
      :root_path
    end
  end

Any idea if it's possible to do that?

Signup page error message in ruby on rails

I am working on my making a sample app from Rails Tutorial by Micheal Hartl. I was working on the errors on my sign up page and I came across an issue im not able to solve.

Screenshot of the error messages

Here after the 5 listed error messages theres an unwanted array listing the same error messages.

Here's the HTML

<%= provide(:title, 'Sign up') %>
<h1>Sign Up</h1>

<div class = "row">
  <div class = "col-md-6 col-md-offset-3">
  <%= form_for(@user) do |f| %>

    <%= render 'shared/error_messages' %>

    <%= f.label :name %>
    <%= f.text_field :name, class: 'form-control' %>

    <%= f.label :email %>
    <%= f.text_field :email, class: 'form-control' %>

    <%= f.label :password %>
    <%= f.password_field :password, class: 'form-control' %>

    <%= f.label :password_confirmation, "Confirmation"%>
    <%= f.password_field :password_confirmation, class: 'form-control' %>

    <%= f.submit "Create My Account", class: "btn btn-primary" %>
    <% end %>
  </div>

And here's the error message partial:

 <% if @user.errors.any? %>
  <div id="error_explaination">
    <div class="alert alert-danger">
      The form contains <%= pluralize(@user.errors.count, "error")%>

    </div>
    <ul>
      <%= @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
      <% end %>
    </ul>
  </div>
<% end %>

And SCSS file:

/* FORMS */
input, textarea, select, .uneditable-input{
  border: 1px solid #bbb;
  width: 100%;
  margin-bottom: 15px;
  @include box_sizing;
}

input{
  height: auto !important;
}

#error_explaination{
  color: red;
  ul{
    color: red;
    margin: 0 0 30px 0;
  }
}

.field_with_errors{
  @extend .has-error;
  .form-control{
    color: $state-danger-text;
  }
}

Help me out. Thanks

popularity is not a multiple-value field, so it cannot index values [0.0]

Hi Have a model named CustomContent with searchable block named popularity

integer :popularity do
  ContentStat.where(content_id: self.content_id, content_type: self.content_type).pluck(:popularity)
end

When tried to create custom_content it is throwing me an error

ArgumentError - popularity is not a multiple-value field, so it cannot index values [0.0]: sunspot (2.2.0) lib/sunspot/field.rb:41:in to_indexed' sunspot (2.2.0) lib/sunspot/field_factory.rb:59:inpopulate_document' sunspot (2.2.0) lib/sunspot/indexer.rb:100:in block in prepare' sunspot (2.2.0) lib/sunspot/indexer.rb:99:inprepare' sunspot (2.2.0) lib/sunspot/indexer.rb:25:in block in add' sunspot (2.2.0) lib/sunspot/indexer.rb:25:inadd' sunspot (2.2.0) lib/sunspot/session.rb:91:in index' sunspot (2.2.0) lib/sunspot/session_proxy/abstract_session_proxy.rb:11:inindex' sunspot (2.2.0) lib/sunspot.rb:184:in `index'

I have done something like below

integer :popularity, :references => ContentStat, :multiple => true do
  ContentStat.where(content_id: self.content_id, content_type: self.content_type).pluck(:popularity)
end

Since I am using this Popularity block for sorting purpose,I can't use multiple true, It's throwing me error saying multi valued block can't be used for sorting

Help me with it

Need a single rails model with dynamic collection name

I have rails model and I am using mongo mapper as ORM. I have two collections with similar attributes and single model. I need to dynamically set collection name in the model based on some condition (user permission) so How I can set dynamically collection name for the model?

Error while starting rails server

I am getting following error while starting server:

/usr/local/rvm/gems/ruby-1.9.3-p551/gems/railties-3.1.6/lib/rails/script_rails_loader.rb:11: warning: Insecure world writable dir /u01/app/oracle/product/11.2.0/dbhome_1/bin in PATH, mode 040777 /usr/lib/ruby/vendor_ruby/bundler.rb:289: warning: Insecure world writable dir /u01/app/oracle/product/11.2.0/dbhome_1/bin in PATH, mode 040777 /usr/local/rvm/gems/ruby-1.9.3-p551/gems/activesupport-3.1.6/lib/active_support/values/time_zone.rb:270: warning: circular argument reference - now /usr/local/rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8/lib/nokogiri.rb:32:inrequire': incompatible library version - /usr/local/rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8/lib/nokogiri/nokogiri.so (LoadError) from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8/lib/nokogiri.rb:32:in rescue in ' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/nokogiri-1.6.8/lib/nokogiri.rb:28:in' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/roo-1.13.2/lib/roo/excelx.rb:2:in require' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/roo-1.13.2/lib/roo/excelx.rb:2:in' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/simple-spreadsheet-0.3.1/lib/simple-spreadsheet/classes/excelx_extended.rb:1:in require' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/simple-spreadsheet-0.3.1/lib/simple-spreadsheet/classes/excelx_extended.rb:1:in' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/simple-spreadsheet-0.3.1/lib/simple-spreadsheet.rb:77:in require' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/simple-spreadsheet-0.3.1/lib/simple-spreadsheet.rb:77:in' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/simple-spreadsheet-0.3.1/lib/simple-spreadsheet.rb:4:in ' from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:77:inrequire' from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:77:in block (2 levels) in require' from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:72:ineach' from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:72:in block in require' from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:61:ineach' from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:61:in require' from /usr/lib/ruby/vendor_ruby/bundler.rb:99:inrequire' from /home/akashk/projects/cymonz-web/rails/config/application.rb:11:in ' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/railties-3.1.6/lib/rails/commands.rb:52:inrequire' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/railties-3.1.6/lib/rails/commands.rb:52:in block in ' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/railties-3.1.6/lib/rails/commands.rb:49:intap' from /usr/local/rvm/gems/ruby-1.9.3-p551/gems/railties-3.1.6/lib/rails/commands.rb:49:in ' from script/rails:6:inrequire' from script/rails:6:in '

lundi 22 mai 2017

How to stub model method for rspec controller test

I'm trying to stub the model method which I'm using in my controller, but it never seems to be working. Can someone let me know the proper way to do it

User Controller

 if current_user.user_token
      @user = @account.users.find(params[:id])
      @user.revoke_seat(:admin, current_user)
      render :template => "/admin/users/revoke_seat"
    else
      render :js => "window.location.href='#{server_url}/oauth/authorize?response_type=code&client_id=#{client_id}&state=#{request.referrer}?auto_revoke_seat=true&redirect_uri=#{auth_service_callback_url}";
    end

Rspec

 before do
    users(:admin).stub(:internal_admin?).and_return(true)
    login_as :admin
    user.stub(:user_token).and_return("123123")
  end

  it "should redirect to authentication service to generate access token" do
      expect(user).to receive(:user_token).and_return(true)
      xhr :put, :revoke_seat, account_id: account.id, id: user.id
      expect(response).to render_template('admin/users/revoke_seat')
      expect(assigns(:account)).to eq(account)
      expect(assigns(:user)).to eq(user)
    end

Rails dropzone how to fix 400 Bad Request?

here's the scenario: after setup the dropzone js, the controller and the routes the dropzone shows 400 Bad Request after upload a file. I added authenticity_token= data-post-url since any ajax request in rails get a error if not include it.

so i would like to know what i missing here.

dropzone js

  $(document).ready(function () {
   Dropzone.autoDiscover = false;
    $('#file').dropzone({// PDF dropzone element
        maxFilesize: 2, // Set the maximum file size to 256 MB
        maxFiles: 10,
        dictDefaultMessage: "drop the files",
        paramName: "proofs[file]",
        addRemoveLinks: true, // Don't show remove links on dropzone itself.
        dictRemoveFile: 'Remover',
        uploadMultiple: true,
       method: 'post',
       acceptedFiles: "image/*",
        url: $('#file').data('post-url')



    });
});


dispute show view

 <div class="dropzone" id="file" data-post-url="<%=  upload_order_dispute_path + '?authenticity_token=' + form_authenticity_token %>"></div>



dispute controller

 def upload
    @dispute = @order.dispute
    respond_to do |format|
      format.json do
        if @dispute.update_attributes(params[:dispute])
          params[:proofs]['file'].each do |a|
            @proof = @dispute.proofs.create!(:file => a)
          end
        end
        render :nothing => true
      end

    end
  end


 routes
 resource :dispute do
post 'upload'=>'dispute#upload'
end

I'm getting a NoMethodError and I'm not sure why

I'm creating a join table that will show me which employee sold which comic. When I type in my employee name It is giving me this error

NoMethodError in Showemployeesales#employeesaleout
undefined method `name_id' for nil:NilClass

Here is my code for my controller

 def employeesaleout
 @employee_name = params[:employee_name_in]
 r = Employee.find_by_name_id(@employee_name)
 @sale_list = r.sales
end

Here is my code for my input view "employeenamein"

   <h1>Showemployeesales#employeenamein</h1>
   <p>Find me in app/views/showemployeesales/employeenamein.html.erb</p>
    <%= form_tag(showemployeesales_employeesaleout_path, :controller => 
    "showemployeesales", :action => "employeesaleout", :method => "post") do 
      %>

    <div class="field">
      <%= label_tag :Employee_Name %><br />
        <%= text_field_tag :employee_name_in %>
    </div>

    <div class="actions">
          <%= submit_tag "Submit Employee Name" %>
    </div>
    <% end %>

Here is my code for my output view

    <center><h1>These are the Sales for <%= @employee_name %> </h1></center>
    <br /> <br />

     <center><table width = 65% border = 1> 
     <tr> <th> Comic Name </th><th> Comic ID </th></tr>   
     <% @sale_list.each do |m| %>     

     <tr> <td> <%= m.product.name_id %> </td> <td> <%= m.product.id_no %> 
     </td></tr>
     <% end %> </table> </center><br /> <br />

And my products table under my schema

   create_table "products", force: :cascade do |t|
   t.string   "name_id"
   t.integer  "id_no"
   t.datetime "created_at", null: false
   t.datetime "updated_at", null: false
   end

What am I doing wrong?

How to schedule a rake tasks in Google Cloud?

I had a Rails application on Heroku, and to schedule some rake tasks I used an add-on called Scheduler. I had to change my application to Google Cloud and I do not know how to schedule the same rakes. Could someone help me?

Rails how create association in the model before or after create?

i'm using a callback to create a association but after the creation did not associate

Someone have any hint how associate in the model instead of in the controller?

class Open < ActiveRecord::Base
after_create :images_build

  def images_build
    images.build

    true
  end
end

I'm getting a undefined method error in Ruby on Rails and I'm not sure why

Basically I have 2 tables called Employees and Sales. I have a form where you input the Employee name and it should show you what phones they have sold. Every time I input the name I get this error

undefined method `sales' for #<Employee:0x007f013e23fdc0>

And it highlights the @sale_list = r.sales part of the code shown below (my controller)

class ShowEmployeeSalesController < ApplicationController
  def employeesaleout
    @employee_name = params[:employee_name_in]
    r = Employee.find_by_name_id(@employee_name)
    @sale_list = r.sales
  end
end

This is my code for the input view:

<h2>
  Please enter the name of the Employee for whom you want to see the sales 
</h2>

<%= form_tag(show_employee_sales_employeesaleout_path, :controller =>  "ShowEmployeeSales", :action => "employeesaleout", :method => "post") do %>
  <div class="field">
    <%= label_tag :Employee_Name %><br />
    <%= text_field_tag :employee_name_in %>
  </div>

  <div class="actions">
    <%= submit_tag "Submit Employee Name" %>
  </div>
<% end %>

This is my code for output view:

<h1>ShowEmployeeSales#employeesaleout</h1>
    <center>
      <h1>
        These are the Sales for <%= @employee_name %> 
      </h1>
    </center><br /> <br />

    <center>
      <table width = 65% border = 1> 
        <tr>
          <th> Phone Name </th>
          <th> Phone ID </th>
        </tr>   
        <% @sale_list.each do |m| %>     
          <tr> 
            <td> 
              <%= m.Mobile %> 
            </td> 
            <td> 
              <%= m.Employee %> 
            </td>
          </tr>
        <% end %> 
      </table> 
    </center><br /> <br />

All of my tables have data in them.

Rails Setup act as commentable gem

after setting the gem everything is working greatly but after post the user comment did save in db someone know why?

the db

Comment id: 12, title: "", comment: nil, commentable_id: 36, commentable_type: "Dispute", user_id: 12, created_at: "2017-05-21 05:27:42", updated_at: "2017-05-21 05:27:42"

dispute controller


 def show
    @dispute = @order.dispute
    @comments = @dispute.comments.all

@comment = @dispute.comments.build(params[:comment])
    @comment.user = current_user
  end

dispite show view

<%= form_for [ @dispute, @comment], :url =>  order_dispute_comments_path  do |f|-%>
  <%= f.text_area :comment %>
  <%= f.submit "Post", :class => "btn_green" %>
<% end -%>




routes

   resources :orders  do 
     resource :dispute do
     resources :comments
   end
end

comments controller

def create
 # @dispute = @dispute.find params[:dispute_id]
    @order = Order.find(params[:order_id])
  @dispute = @order.dispute
  @comment = @dispute.comments.new params[:comment]
  @comment.user = current_user

  if @comment.save
   redirect_to order_dispute_path
  end
end
end

Uservoice classic widgets appears in production environment but doesn't appear in developpement environement

I got ruby on rails project that i just install in my localhost, this project contains some uservoice classic widgets. these widgets appear on the hosted project and whenever I try run rails s in my localhost the project started without showing these widgest. when I try rails s -e production th widgest appear on the project.

Can you please explain to me this issue ? and how can I let the widgest runs in developement environement while running rails s

Thank you

Joining two or more tables in Rails?

I have 3 tables Ledgers, Accounts, Users and organisation

I am trying to get accounts using ledger Id for each specific user.

Table Ledgers contains - LedgerID, Organisation ID
Table Accounts contains  - AccountID, AccountName, LedgerID
Table Users contains - UserID, name
Table Organisation contains - OrganisationId, UserID, organisation name

Heres my models.

class Accounts < ActiveRecord::Base
  belongs_to :ledger
end

class Ledger < ActiveRecord::Base
  has_many :accounts
  belongs_to :organisation
end

class User < ActiveRecord::Base
  has_many :organisations
end

Here is what i have tried.

def show
  if authenticated_user
  @Usersorganisations = @authenticated_user.organisations
  # This gets the user's organisations
  @ledger_id = Ledger.where("organisation_id = ?", @Usersorganisations.pluck(:id))

  render json: @ledger_id.as_json
end

But trying this gives me PG::DatatypeMismatch: ERROR:

UserVoice is not defined

I am working on project that use uservoice classic widget. The uservoice classic widget works good in hosted version of the project: whenever i click the link i got the popup classic widget. But when I got run the project in localhost when I click the link I receive this error in console of my browser UserVoice is not defined I am working with Rails 3.2 Thank you for any suggestions.

select option des not work in rails

I am trying to display the value have chosen, but it does not seem to be working. Any ideas?

Here is the code:

    <label>Apply to <%= statement_display_name.downcase %>:</label> <%= 
    f.select( :statement_id, 
    options_for_select(@client.statements.unpaid.collect { |statement| 
    [statement_display_name + " #{statement.number_with_prefix} #
    {statement.created_or_bill_date.to_date} - #
    {number_to_currency(statement.outstanding_amount)}"]}), :selected 
     => f.object.statement_id )%>

Submit button with Options

For one form, I want to have two submit buttons , named:

Appove, Decline

when the user clicks on Approve it should send approve: true as well

when the user clicks on Decline it should send approve: false as well

Basically the buttons should work like a checkbox

Is this possible with Rails and how to implement it? Thanks

How to initialise a method in a ruby class on rails server start up

I have created ruby thread which keep polling messages from Queue. The following is the basic code block which keeps polling the queue infinitely.How could i initialise this method (poll method in class Poller ) on rails server start up so that this code(infinite loop thread) block runs when the application starts

class Poller
 class << self
  def poll
    begin 
      ----polling logic for queue
      sleep(1.minute)
    end while(true)
  end

 end
end

How do i initialise above code in a rails initialisers so that the above code will start polling messages from queue?

TinyTds::Error: Invalid length parameter passed to the LEFT or SUBSTRING function

This is an update statement - which throws the below error when executed . I haven't used LEFT or Substring hence cannot understand what the error means

TinyTds::Error: Invalid length parameter passed to the LEFT or SUBSTRING function.: EXEC sp_executesql N'UPDATE [table] SET [status_description] = N''Completed successfully'', [status] = N''completed'', [updated_at] = ''2017-05-18T02:33:13.387'' WHERE [table].[id] = 23344; SELECT @@rowcount AS AffectedRows'

The table gets updated though

dimanche 21 mai 2017

Rails how create association in the model before or after create?

i'm using a callback to create a association but after the creation did not associate

Someone have any hint how associate in the model instead of in the controller?

class Open < ActiveRecord::Base
after_create :images_build

  def images_build
    images.build

    true
  end
end

I'm getting a undefined method error in Ruby on Rails and I'm not sure why

Basically I have 2 tables called Employees and Sales. I have a form where you input the Employee name and it should show you what phones they have sold. Every time I input the name I get this error

undefined method `sales' for #<Employee:0x007f013e23fdc0>

And it highlights the @sale_list = r.sales part of the code shown below (my controller)

  `class ShowEmployeeSalesController < ApplicationController
   def employeesaleout
    @employee_name = params[:employee_name_in]
    r = Employee.find_by_name_id(@employee_name)
     @sale_list = r.sales
   end`

This is my code for the input view:

     `<h2>Please enter the name of the Employee for whom you want to see the 
      sales </h2>

       <%= form_tag(show_employee_sales_employeesaleout_path, :controller => 
      "ShowEmployeeSales", :action => "employeesaleout", :method => "post") 
      do %>

    <div class="field">
      <%= label_tag :Employee_Name %><br />
        <%= text_field_tag :employee_name_in %>
     </div>

    <div class="actions">
          <%= submit_tag "Submit Employee Name" %>
   </div>
     <% end %>

` This is my code for output view:

       `<h1>ShowEmployeeSales#employeesaleout</h1>
         <center><h1>These are the Sales for <%= @employee_name %> </h1>
        </center><br /> <br />

        <center><table width = 65% border = 1> 
          <tr> <th> Phone Name </th><th> Phone ID </th></tr>   
        <% @sale_list.each do |m| %>     

     <tr> <td> <%= m.Mobile %> </td> <td> <%= m.Employee %> </td></tr>
     <% end %> </table> </center><br /> <br />`

All of my tables have data in them.

samedi 20 mai 2017

Rails Setup act as commentable gem

after setting the gem everything is working greatly but after post the user comment did save in db someone know why?

the db

Comment id: 12, title: "", comment: nil, commentable_id: 36, commentable_type: "Dispute", user_id: 12, created_at: "2017-05-21 05:27:42", updated_at: "2017-05-21 05:27:42"

dispute controller


 def show
    @dispute = @order.dispute
    @comments = @dispute.comments.all

@comment = @dispute.comments.build(params[:comment])
    @comment.user = current_user
  end

dispite show view

<%= form_for [ @dispute, @comment], :url =>  order_dispute_comments_path  do |f|-%>
  <%= f.text_area :comment %>
  <%= f.submit "Post", :class => "btn_green" %>
<% end -%>




routes

   resources :orders  do 
     resource :dispute do
     resources :comments
   end
end

comments controller

def create
 # @dispute = @dispute.find params[:dispute_id]
    @order = Order.find(params[:order_id])
  @dispute = @order.dispute
  @comment = @dispute.comments.new params[:comment]
  @comment.user = current_user

  if @comment.save
   redirect_to order_dispute_path
  end
end
end

Uservoice classic widgets appears in production environment but doesn't appear in developpement environement

I got ruby on rails project that i just install in my localhost, this project contains some uservoice classic widgets. these widgets appear on the hosted project and whenever I try run rails s in my localhost the project started without showing these widgest. when I try rails s -e production th widgest appear on the project.

Can you please explain to me this issue ? and how can I let the widgest runs in developement environement while running rails s

Thank you

Joining two or more tables in Rails?

I have 3 tables Ledgers, Accounts, Users and organisation

I am trying to get accounts using ledger Id for each specific user.

Table Ledgers contains - LedgerID, Organisation ID
Table Accounts contains  - AccountID, AccountName, LedgerID
Table Users contains - UserID, name
Table Organisation contains - OrganisationId, UserID, organisation name

Heres my models.

class Accounts < ActiveRecord::Base
belongs_to :ledger

class Ledger < ActiveRecord::Base
has_many :accounts
belongs_to :organisation

class User < ActiveRecord::Base
has_many :organisations

Here is what i have tried.

def show
 if authenticated_user
 @Usersorganisations = @authenticated_user.organisations
  /This gets the user's organisations/

 @ledger_id = Ledger.where("organisation_id = ?", @Usersorganisations.pluck(:id))

 render json: @ledger_id.as_json
end

But trying this gives me PG::DatatypeMismatch: ERROR:

vendredi 19 mai 2017

UserVoice is not defined using Rails

I am working on project that use uservoice classic widget. The uservoice classic widget works good in hosted version of the project: whenever i click the link i got the popup classic widget. But when I got run the project in localhost when I click the link I receive this error in console of my browser UserVoice is not defined I am working with Rails 3.2 Thank you for any suggestions.

select option des not work in rails

I am trying to display the value have chosen, but it does not seem to be working. Any ideas?

Here is the code:

    <label>Apply to <%= statement_display_name.downcase %>:</label> <%= 
    f.select( :statement_id, 
    options_for_select(@client.statements.unpaid.collect { |statement| 
    [statement_display_name + " #{statement.number_with_prefix} #
    {statement.created_or_bill_date.to_date} - #
    {number_to_currency(statement.outstanding_amount)}"]}), :selected 
     => f.object.statement_id )%>

Submit button with Options

For one form, I want to have two submit buttons , named:

Appove, Decline

when the user clicks on Approve it should send approve: true as well

when the user clicks on Decline it should send approve: false as well

Basically the buttons should work like a checkbox

Is this possible with Rails and how to implement it? Thanks

jeudi 18 mai 2017

Rails: Find all mailer actions triggered from a given action

I am working on a code not written by me. There is a big Controller action. Someone knows a way to find all the Mailer actions triggered from this Controller action? (A Mailer action can be triggered also from outside of the Controller (from a model method for instance))

How to initialise a method in a ruby class on rails server start up

I have created ruby thread which keep polling messages from Queue. The following is the basic code block which keeps polling the queue infinitely.How could i initialise this method (poll method in class Poller ) on rails server start up so that this code(infinite loop thread) block runs when the application starts

class Poller
 class << self
  def poll
    begin 
      ----polling logic for queue
      sleep(1.minute)
    end while(true)
  end

 end
end

How do i initialise above code in a rails initialisers so that the above code will start polling messages from queue?

TinyTds::Error: Invalid length parameter passed to the LEFT or SUBSTRING function

This is an update statement - which throws the below error when executed . I haven't used LEFT or Substring hence cannot understand what the error means

TinyTds::Error: Invalid length parameter passed to the LEFT or SUBSTRING function.: EXEC sp_executesql N'UPDATE [table] SET [status_description] = N''Completed successfully'', [status] = N''completed'', [updated_at] = ''2017-05-18T02:33:13.387'' WHERE [table].[id] = 23344; SELECT @@rowcount AS AffectedRows'

The table gets updated though

mercredi 17 mai 2017

Rails how to change status on a method?

i'm trying to change the status of Dispute object on create and update

i did the attribute inside the method but the status did not changed.

Is better to change the status in the model with callback instead on controller?

def create


   Dispute.new 

    if params[:status] == 'Open'
      dispute.status = dispute.statuses[0]
    end

    if dispute.save

       redirect_to dispute_path(@dispute)
      flash[:success] = 'Hooray'

  else
    flash[:error] = 'Error'
  redirect_to :back
end

end

on Dispute model

class Dispute < ActiveRecord::Base

  STATUSES = %w(open finished).freeze
  STATUSES.each do |method|
    define_method "#{method}?" do
      status == method
    end
  end

  def self.statuses
    STATUSES
  end

end

how to build a record with multiple references with has many association in rails

I have 3 models named Article, User, Comment

class Article < ActiveRecord::Base
  has_many :comments
end

class User < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :user
  belongs_to :article
end

Now, if I want to build a comment for an article, I can use

@comment = @article.comments.build(comment_params)

this will add article_id to the comment object

Now, if I want to add the user_id to object, I can add in the following way

@comment.user_id = current_user.id

But, if I want to auto populate user_id like article_id, what way I can do?

Error "get 404 not found" in jquery rails

My error in console of browser:

GET http://server/assets/headhesive/options-f302fd8c6dff844c32b94df2780bdbdb.js 404 (Not Found)

At the end of the file layouts/application.html.haml:

= javascript_include_tag 'headhesive/headhesive'
= javascript_include_tag 'headhesive/options'

And if I do so:

%script{src: 'assets/headhesive/headhesive.js'}
%script{src: 'assets/headhesive/options.js'}

it works only on root page (though in production I haven't checked).
How to fix this error?

mardi 16 mai 2017

datetime saved in database but when i want to call the datetime it is a nil value

I have a datetime, called due_date, that gets saved in agreement table. When i want to display the datetime, it just gives me nil, however Im looking at my db row and its clearly not nil. must be some sort of formating problem.. im using mountain time zone for my whole application as the datetime value called due_date needs to be my timezone anyways. the reason is my due_date is set to the end of the day and i want it to be specifically mountain time. Im using rails and postgres.

As you can see I have an agreement with the due_date entered.. now when i want to display the due_date value it gives me nil. enter image description here

application.rb

 config.time_zone = 'Mountain Time (US & Canada)'
 config.active_record.default_timezone = :local

All in all how can I display @agreement.due_date and give me the same date from the db?

  • also a note is from the picture is that when i try @agreement.created_at it shows up just fine unlike the due_date

Getting duplicate data from the controller that is not there

please bear with me as I am quite new to this.

I have the following code in the controller:

@xform = Form.where(:x_id == current_user.id) @yform = Form.where(:y_id == current_user.id)

and the corresponding code in the view:

I'm getting the issue in which both the xforms and yform are returning the same file name into the view. What is causing this issue and how do i fix this. Thanks!

How to includes or join into with a each method?

I'm discovering the methods join & includes with rails. Which are great, but I'm not really fluent with it, so I need a little advice about it.

I explain my situation, I'm displaying a list of groups into the index view. Each of them have a modal associated. And into this modal, I would like to display a list of the requests associated to this group. So normally, I user the fonction [ @requests = group.requests ]. But I would like to use join for that for sending just one request to my sql.

Because i'm in the index view, I don't have a @group into my action. So how I can do that ?

My code :

controller :

def index
  @groups = current_user.groups
end 

view (index) :

<% @groups.each do |g| %>
  <MODAL>
    <% @requests = g.requests %>
    <% @requests.each do |r| %>
      <%= r.date %>
    <% end %>
  </MODAL>
<% end %>

I guess I can also use join & include for @groups, but there is already just one sql request, so I'm good with it.

Rails how to form post one object on another object view?

I have dispute object that belongs to order and i would like to create it on orders view so: How can create a object on another object page?

the route is:

dispute_sent_order_path(@order), :html => {:method => :post} do |f| %>
 resources :orders, only: [:index, :update, :destroy] do

    member do

get :dispute
post :dispute_sent
put :dispute_done

end
end




 def dispute
   @order = current_user.orders.find(params[:id])
    if current_user.address.blank?
      redirect_to edit_user_path

      flash[:error] = 'error'
    else
      @dispute = Dispute.new
    end
  end 


def dispute_sent

@order = current_user.orders.find(params[:id])
  if   current_user == @order.buyer
    dispute = @order.dispute.nil? ? Dispute.new : @order.dispute
     params[:status] == 'Open'
    if dispute.save
      flash[:success] = 'hooray'
    end
  else
    flash[:error] = 'Error'
  end
  redirect_to :back
end
end

Rails how to associate 2 models on create?

I would like to associate Order object wit Dispute Object on create of Dispute but when i go create the object in the log shows:

ActiveRecord::RecordNotFound (Couldn't find Order without an ID)

should i not try to find the order in the method?

Someone know how to associate the objects in the creation?

the Dispute Controller is:

class DisputesController < ApplicationController

  def new

    if current_user.address.blank?
      redirect_to edit_user_path

      flash[:error] = 'fill the address'
    else
      @dispute = Dispute.new

    end
  end 



def create
 @order = Order.find(params[:id])
  if   current_user == @order.buyer
    dispute = @order.dispute.nil? ? Dispute.new : @order.dispute
    dispute.attributes = params[:dispute]
    dispute.user = @order.buyer
    dispute.buyer_name = @order.buyer_name
    dispute.seller_name = @order.seller_name

    if dispute.save
      flash[:success] = 'Dispute Created'
    end

end

The order model

class Order < ActiveRecord::Base

has_one :dispute

end

the dispute model

class Dispute < ActiveRecord::Base

belongs_to :order

end

Gems are not being installed from after capistrano deployment

I am using rails 4.2, unicorn app server and nginx web server, I am using capistrano for deployment.

If I am adding a gem to gemfile its not reflecting in the application. I tried to check a gem by Gem.loaded_specs["koala"].full_gem_path but its not showing anywhere. Also I can see one error in capistrano logs

cd /home/deploy/bloom/releases/20170516105043 && RAILS_ENV=dev bundle exec honeybadger deploy --environment dev --revision 08e4726 --repository git@bitbucket.org:appster/bloom-ruby.git --user arvindmehra
DEBUG[1450b9f0]     **bash: bundle: command not found**

Here is my capfile:

#

require 'capistrano/setup'
require 'capistrano/deploy'
require 'capistrano/bundler'
require 'capistrano/honeybadger'
require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano/rvm'
require 'whenever/capistrano'

Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

Here is my deployment environment script from dev.rb

set :branch, 'dev'
set :keep_releases, 3

server '66.128.61.239',
  user: 'deploy',
  roles: %w{web app db},
  ssh_options: {
    user: 'deploy', # overrides user setting above
    keys: %w(~/.ssh/id_rsa),
    forward_agent: false,
    #auth_methods: %w(publickey)
    password: 'password'
  }


 namespace :deploy do

  %w[start stop restart].each do |command|
    desc "#{command} unicorn server"
    task command do
      on roles(:app), in: :sequence, wait: 1 do
         execute "/etc/init.d/bloom-ruby #{command}"
      end
    end
  end

  after :publishing, :restart

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      # Here we can do anything such as:
      # within release_path do
      #   execute :rake, 'cache:clear'
      # end
    end
  end

end

Here is my deploy.rb

# config valid only for current version of Capistrano
lock '3.3.3'


set :application, 'bloom'
set :repo_url, 'git@bitbucket.org:appster/bloom-ruby.git'
set :deploy_to, '/home/deploy/bloom'
#set :linked_files, fetch(:linked_files, []).push('config/database.yml', 'config/secrets.yml')

# Define which type of RVM the server is using
set :rvm_type, :user
set :rvm_ruby_version, '2.2.2@bloom'

# Default value for :linked_files is []
set :linked_files, %w{config/database.yml config/secrets.yml config/settings.yml config/providers.yml config/stripe.yml}

# Default value for linked_dirs is []
set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/identicons public/uploads public/images}

How to use multiple cases in ruby

  case value and filter
    when "sale", "with"

    when "rent", "with"

    when "sale", "without"

    when "rent", "without"

  end

In the above statement it doesnt throw error but fail to work as expected. the case value is not accounted.

Is there any tweek to use multiple cases. here, I need to account both "value" and "filter"

lundi 15 mai 2017

How to match a single character in string with regex?

Hi i'm using regex to match a string

str = Milk

str.match(/^.*?lk.*?$/i)

For single character this is fine. How can check the whole string and replace the matched character using ruby regex pattern?

Rails why undefined local variable or method `new_dispute' for #

i added dispute new link inside orders but rails log shows

since the dispute is associated with order in the model why still show undefined local variable or method?

undefined local variable or method `new_dispute' for

<#

someone know why?

view/_order.html.erb

        <ul>
     <li>Order: <b><%= order.transaction.transaction_id %></b></li>
      <li>seller:<%= order.seller_name %></li>
 <li><%=link_to"Create New Dispute", new_dispute %></li>
</ul>

disputer controller


class DisputesController < ApplicationController

  def new
    @order = current_user.cart.orders.find(params[:id])
    if current_user.address.blank?
      redirect_to edit_user_path
      flash[:error] = 'error'
    else
      @dispute = Dispute.new
    end
  end 
end

class Order < ActiveRecord::Base

  has_one :dispute


end


class Dispute < ActiveRecord::Base
  # attr_accessible :title, :body


  belongs_to :order
'

end

rake aborted! StandardError: An error has occurred, this and all later migrations canceled: PG::Error: ERROR:

I have an issue, concerning migration on Ruby on Rails 3.2.16. I got a project that i should run on my localhost, whenver I run bundle exec rake db:migrate some tables are created on my database ( postgreesql) and others are aborted because of a select query with error:

rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::Error: ERROR:  column "column_name" does not exist

this error comes from a select query while executing the command line mentioned above.

Thank you in advance.

how to display map on pdf with wicked_pdf in rails?

I am using wicked_pdf for generating pdf in my rails application.

I need to display a map on pdf with iframe.

I used bellow code for the map.

%iframe{:frameborder => "0", :height => "200", :src => "http://ift.tt/1mEJKQl{spot_details.lat}, #{spot_details.lng}&hl=es;z=14&output=embed", :style => "border:0;width:100%;margin-bottom:20px"}

But it gives me simple frame without map like this http://ift.tt/2qk18CV

Anyone, please suggest me how to display map on wicked_pdf with rails application.

How to set offset rule using "recurring_select" gem

How to set offset rule using recurring_select gem? Say I have set some recurring event which falls on Saturday and Sunday on any upcoming month, then I have to alter the date to the next working day for that month.

dimanche 14 mai 2017

Ruby on Rails inheritance?

I've seen a bunch of rails "inheritance" models but any of them makes sense for me What is the right way to use inheritance in rails?

Model Person with name, address Model User > Person, with all of the attributes of Person plus user and password

thanks!

Resolution Center gem or engine for rails

Somebody Know some gem or engine for create a small Resolution Center for rails?

at first i thought a ticket system but. but Resolution Center seems more complicated than that.

Rails aborted error message

I'm getting an error while running the following test $ rails test:models

Below is a sample of the error:

Run options: --seed 40805 Finished in 0.046173s, 21.6575 runs/s, 21.6575 assertions/s. rails aborted! ArgumentError: wrong number of arguments (given 1, expected 0) /usr/local/rvm/gems/ruby-2.3.1/gems/railties-5.0.0.1/lib/rails/test_unit/minitest_plugin.rb:9:in aggregated_results' /usr/local/rvm/gems/ruby-2.3.1/gems/minitest-5.10.2/lib/minitest.rb:597:inreport'

Any help would be greatly appreciated!

samedi 13 mai 2017

Rails How to fix Missing mobile template?

i'm trying to update the user information when on mobile but rails log show:

someone know why this happen on mobile mode?

Missing template users/update, application/update with {:locale=>[:"en"], :formats=>[:mobile], :handlers=>[:erb, :builder, :coffee]}. Searched in:

def update
    @user = User.find(params[:id])
    respond_to do |format|
      format.html do
        @states = State.all
        @cities = City.where('state_id = ?', State.first.id)
        if @user.update_attributes(params[:user])
          redirect_to(action: :edit, id: @user, only_path: true, format: :html)
          flash[:notice] = 'updated'

        else
          render :edit
        end
      end
      format.json do
        @user.update_attributes(params[:user])
        render nothing: true
      end
    end
  end

Getting information from models

I have 3 models in my web app. One is for the posts, the remaining models are used to populate the columns in my post model. The POST model has the following columns:

  • ID
  • Type of animal
  • Species

The other 2 models and their columns are;

TYPE OF ANIMAL:


  • ID
  • Name

SPECIES:

  • ID
  • Name
  • Skin Colour
  • Eye colour

When I create a new object of the POST model, I can choose the names from TYPE OF ANIMAL and SPECIES. Now, in my show view, how can I have access to the other columns of my selected SPECIES model. Lets say I have 10 different species models and I choose number 3, how can I show the information in the skin colour and eye colour columns.

vendredi 12 mai 2017

Intalling Rails in windows activesupport requires Ruby version >= 2.2.2

I have a problem installing rails on my computer.

ruby -v 
ruby 2.3.3p222 (2016-11-21 revision 56859) [x64-mingw32]

I get this error message :

ERROR: Error installing rails: activesupport requires Ruby version >= 2.2.2.

How can I install rails?

Changing the data of a f.label after the user presses f.submit

So I currently have this code in the html.erb:

<%= f.label :user_id => %>
<%= f.email_field :user_id %>

I want the user to enter an email into the email_field in which it converts it into user_id using this:

User.find_by_email("xyz@abc.com")

However, I have no idea how to use it or know whether this will even work. Will appreciate some help on this as I am quite new to rails. Thanks!

can't convert Hash into Integer (TypeError)

CSV file I have 1000 files in one directory. I want to call all teh csv files in that directory and execute if condition. if condition satisfies it should print name else nothing Example of csv name,id,address,country,food A,11,bcvhcbdc,india,biryani ...

require "csv"
path="/logs/*exception_evaluation_summary.csv"
#calling csv files in the directory
Dir.glob(path).each do |f|
#reading csv files
csv = CSV.read(f, :headers=>true, :encoding => "bom|utf-8")
csv.each do |record|
if (record['id'] != 0 && record['country']=="india" && record['food']=="biryani") 
print record[name]
else
print "nothing"
end

Plot a Morris chart line in RUBY ON RAILS

i'm using the MORRIS JS to plot a chart line in my Ruby On Rails Project

I retreive Data from my Database : MYSQL and want to plot it in Morris JS CHART

I return an Array of data from Database. My Problem: is that the MORRIS JS , just plot the first row of my array , i don't know dose not plot all the data retreived from MYSQL DATABASE.

Please, i need help

So this my Code

My controller

     require 'json'

    @get_data =  CttGueHydro2Aae.where("Date_YMDHMS  >= '2017-05-10 16:10:12'")
    #@get_data  = CttGueHydro2Aae.all

    @chart_data = Array.new
    obj = {}

    obj["time"] = " "
    obj["value"] = " "

    @get_data.each do |data|
        obj["time"] = data.Date_YMDHMS
        obj["value"] = data.AAE_8062
        @chart_data.push(obj)
    end
     #Json Conversion
    @chart_data = @chart_data.to_json



  end

View>Index.html.erb

<div id="myfirstchart" style="height: 250px;"></div>





<script type="text/javascript">


new Morris.Line({
  // ID of the element in which to draw the chart.
  element: 'myfirstchart',
  // Chart data records -- each entry in this array corresponds to a point on
  // the chart.
  data: <%= @chart_data.html_safe %>,
  // The name of the data record attribute that contains x-values.
  xkey: 'time',
  // A list of names of data record attributes that contain y-values.
  ykeys: ['value'],
  // Labels for the ykeys -- will be displayed when you hover over the
  // chart.
  labels: ['Value']
});


</script>

So, when i run the Server from command line : rails s Just the Morris plot the first value of my array

PLOT IN MY BROWSER from the DEBEGUER of MY BROWSER i get this :

Inspector of my code in the browser

All

Rails engine latest commit not reflecting in host application

I have an application which is using rails engine.

route file of host application named as crowd

Rails.application.routes.draw do
    mount Crowd::Engine => "/"
end

Gemfile

gem 'crowd',  git: 'git@bitbucket.org:arvind/crowd.git',  ref: '56d948518f11cab64a4d6213fb098288175a4665'   #this is the latest commit

I am able to access the code from rails engine, but the problem is whatever new code I am commiting in rails engine is not reflecting in my production instance. Although I am able to access the latest code commit on localhost but not on production after deployment.

The funny thing the latest code of engine is accessible from rails console in production. But it doesnt reflect when accessed from IP of that server.

The app consists:

 1. Memcached server
 2. Elasticsearch server
 3. sidekiq server
 4. Mysql server

I am deploying application using capistrano. I have observed that at one point bundling of honeybadger fails down at time of deployment, but in the end it gets completed successfully can it be related?

cap logs:

DEBUG[75f8aa4f] Finished in 0.636 seconds with exit status 0 (successful).
INFO[98954a51] Running RAILS_ENV=dev bundle exec honeybadger deploy --environment dev --revision e679be0 --repository git@bitbucket.org:prem/boold-ruby.git --user prem on 66.228.62.229
DEBUG[98954a51] Command: cd /home/deploy/boold/releases/20170512042820 && RAILS_ENV=dev bundle exec honeybadger deploy --environment dev --revision e679be0 --repository git@bitbucket.org:prem/boold-ruby.git --user prem
DEBUG[98954a51]     bash: bundle: command not found
INFO[98954a51] Finished in 0.556 seconds with exit status 127 (failed).
INFOHoneybadger notification complete.
DEBUG[a97f49cf] Running /usr/bin/env if test ! -d /home/deploy/boold/releases; then echo "Directory does not exist '/home/deploy/boold/releases'" 1>&2; false; fi on 66.228.62.229
DEBUG[a97f49cf] Command: if test ! -d /home/deploy/boold/releases; then echo "Directory does not exist '/home/deploy/boold/releases'" 1>&2; false; fi
DEBUG[a97f49cf] Finished in 0.760 seconds with exit status 0 (successful).
INFO[588e79b7] Running /usr/bin/env echo "Branch dev (at e679be0) deployed as release 20170512042820 by prem" >> /home/deploy/boold/revisions.log on 66.228.62.229
DEBUG[588e79b7] Command: echo "Branch dev (at e679be0) deployed as release 20170512042820 by prem" >> /home/deploy/boold/revisions.log
INFO[588e79b7] Finished in 0.555 seconds with exit status 0 (successful).

jeudi 11 mai 2017

C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.0/lib/selenium/webdriver/common/service.rb:59:in `binary_path

I'm new to Ruby and I have very little practice. I'm having difficulty compiling the instabot that is demonstrated in the following video: Build an Instagram autofollow bot

The error message is:

C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.0/lib/selenium/webdriver/common/service.rb:59:in `binary_path':  Unable to find chromedriver. Please download the server from http://ift.tt/1hV5c2G and place it somewhere on your PATH. More info at http://ift.tt/1MNpI1r. (Selenium::WebDriver::Error::WebDriverError)
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.0/lib/selenium/webdriver/common/service.rb:49:in `initialize'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.0/lib/selenium/webdriver/chrome/bridge.rb:47:in `new'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.0/lib/selenium/webdriver/chrome/bridge.rb:47:in `initialize'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.0/lib/selenium/webdriver/common/driver.rb:61:in `new'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.0/lib/selenium/webdriver/common/driver.rb:61:in `for'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.4.0/lib/selenium/webdriver.rb:88:in `for'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/watir-6.2.1/lib/watir/browser.rb:46:in `initialize'
        from auto_follow.rb:16:in `new'
        from auto_follow.rb:16:in `<main>'

My code is like this:

require 'watir' # Crawler
require 'pry' # Ruby REPL
require 'rb-readline' # Ruby IRB
require 'awesome_print' # Console output
require_relative 'credentials' # Pulls in login credentials from credentials.rb

username = $username
password = $password
users = ["josephineskriver", "theweeknd", "kendalljenner", "karliekloss"]
follow_counter = 0
unfollow_counter = 0
MAX_UNFOLLOWS = 200
start_time = Time.now

# Open Browser, Navigate to Login page
browser = Watir::Browser.new :chrome, switches: ['--incognito']
browser.goto "http://ift.tt/1pHgwUl"

# Navigate to Username and Password fields, inject info
puts "Logging in..."
browser.text_field(:name => "username").set "#{username}"
browser.text_field(:name => "password").set "#{password}"

# Click Login Button
browser.button(:class => '_ah57t _84y62 _i46jh _rmr7s').click
sleep(2)
puts "We're in #hackerman"

# Continuous loop to run until you've unfollowed the max people for the day
loop do
  users.each { |val|
    # Navigate to user's page
    browser.goto "http://ift.tt/2r60sil"

    # If not following then follow
    if browser.button(:class => '_ah57t _84y62 _frcv2 _rmr7s').exists?
      ap "Following #{val}"
      browser.button(:class => '_ah57t _84y62 _frcv2 _rmr7s').click
      follow_counter += 1
    elsif browser.button(:class => '_ah57t _6y2ah _frcv2 _rmr7s').exists?
      ap "Unfollowing #{val}"
      browser.button(:class => '_ah57t _6y2ah _frcv2 _rmr7s').click
      unfollow_counter += 1
    end
    sleep(1.0/2.0) # Sleep half a second to not get tripped up when un/following many users at once
  }
  puts "--------- #{Time.now} ----------"
  break if unfollow_counter >= MAX_UNFOLLOWS
  sleep(30) # Sleep 1 hour (3600 seconds)
end

ap "Followed #{follow_counter} users and unfollowed #{unfollow_counter} in #{((Time.now - start_time)/60).round(2)} minutes"

# Leave this in to use the REPL at end of program
# Otherwise, take it out and program will just end
Pry.start(binding)

# Top 100 users on Instagram
# users = ['instagram', 'selenagomez', 'arianagrande', 'taylorswift', 'beyonce', 'kimkardashian', 'cristiano', 'kyliejenner', 'justinbieber', 'kendalljenner', 'nickiminaj', 'natgeo', 'neymarjr', 'nike', 'leomessi','khloekardashian', 'mileycyrus', 'katyperry', 'jlo', 'ddlovato', 'kourtneykardash', 'victoriasecret', 'badgalriri', 'fcbarcelona', 'realmadrid', 'theellenshow', 'justintimberlake', 'zendaya' 'caradelevingne', '9gag', 'chrisbrownofficial', 'vindiesel', 'champagnepapi', 'davidbeckham', 'shakira', 'gigihadid', 'emmawatson', 'jamesrodiguez10', 'kingjames', 'garethbale11', 'nikefootball', 'adele', 'zacefron', 'vanessahudgens', 'ladygaga', 'maluma', 'nba', 'nasa', 'rondaldinho', 'luissuarez9', 'zayn', 'shawnmendes', 'adidasfootball', 'brumarquezine', 'hm', 'harrystyles','chanelofficial', 'ayutingting92', 'letthelordbewithyou', 'niallhoran', 'anitta', 'hudabeauty', 'camerondallas', 'adidasoriginals', 'marinaruybarbosa', 'lucyhale', 'karimbenzema', 'princessyahrini', 'zara', 'nickyjampr', 'onedirection', 'andresiniesta8', 'raffinagita1717', 'krisjenner', 'manchesterunited', 'natgeotravel', 'marcelottwelve', 'deepikapadukone', 'snoopdogg', 'davidluiz_4', 'kalbiminrozeti', 'priyankachopra', 'ashleybenson', 'shaym', 'lelepons', 'prillylatuconsina96','louisvuitton','britneyspears', 'sr4official', 'jbalvin', 'laudyacynthiabella', 'ciara', 'stephencurry30', 'instagrambrasil']

C:/Ruby23-x64/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- watir (LoadError)

I'm new to Ruby and I have very little practice. I'm having difficulty compiling the instabot that is demonstrated in the following video: Build an Instagram autofollow bot

The error that appears is:

C:/Ruby23-x64/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- watir (LoadError)
        from C:/Ruby23-x64/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from auto_follow.rb:1:in `<main>'

My code is like this:

require 'watir '
require_relative 'credentials'

username = $username
password = $password

user = 'justinbieber'

#abrir o browser e navegar até a página de login

browser = Watir::Browser.new :chrome
browser.goto = "http://ift.tt/1OyNf88"

#navegando para os campos de login e senha e injetando informações
puts "Login in..."
browser.text_field(:name => "username").set "#{username}"
browser.text_field(:name => "password").set "#{password}"


#clicando no botao
browser.button(:class => '_ah57t _84y62 _i46jh _rmr7s').click

sleep(360)

Rails route not found even when its present

My following API route is not found when hit with CURL or POSTMAN client

Started POST "/api/users/register_handheld" for 181.74.100.34 at 2017-05-11 11:27:42 +0000
DEBUG: Chewy strategies stack: [2] <- atomic @ /home/deploy/boold/shared/bundle/ruby/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17

ActionController::RoutingError (No route matches [POST] "/api/users/register_handheld"):

But when i check my routes using routes this URL is present.

enter image description here

This URL actually works if I hit in rails console

app.post "/api/users/register_handheld"
Started POST "/api/users/register_handheld" for 127.0.0.1 at 2017-05-11 11:21:03 +0000
DEBUG: Chewy strategies stack: [3] <- atomic @ /home/deploy/boold/shared/bundle/ruby/2.2.0/gems/chewy-0.8.4/lib/chewy/railtie.rb:17
Processing by Crowd::Api::V1::HandheldUsersController#create as JSON

How to return the correct fields in Rails API ?

I have these two tables - User, Accounts. User contains an authentication key, Accounts contains the list of accounts.

I am trying to get the list of accounts for the user if the authentication key is correct.

So in the controller I have -

    def show

         @user = User.where(authentication_token:params[:authentication_token])
            render json: @user.as_json(only: 
            [:email,:id,:authentication_token]),status: :created

end

This would just return the user details. How can i edit it so it first checks if the user exists with that Authentication_token, and then uses the UserID, in the accounts table to get the list of accounts ?

mercredi 10 mai 2017

Merge two active record using or merge in Rails 3.2, ActiveRecord 3.2

I have two different queries that I need to merge into one query (so I can use will_paginate).

After they are merged I need to group_by :date.

Then I need to apply paginate to it.

results1 = Mission.joins(:track => { :track_subscriptions => :member }).where("member_id = ?", current_member.id)
results2 = Mission.joins(:track).merge(Track.visibility_unsubscribables)
finalresults = results1.or(results2) 
finalresults.group_by { |r| r[:date] }
finalresults.paginate(:page => params[:page], :per_page => 30)

This doesn't work because I don't have ActiveRecord 5+, and I can't get will_paginate to work with grouped results.

Is there a better way to approach this?

Why won't the Delayed Job error callback execute?

I am trying to follow this guide about handling API rate limits with Delayed Job.

Here is my job:

# app/jobs/mailer_job.rb
class MailerJob < Struct.new(:custom_id)

  def perform
    # Intentionally throw an error to test error callback
    raise StandardError
  end

  def error(job, exception)
    puts 'Error!'
  end

end

Here are the potentially related gems I have installed. I am using Ruby 1.9.3.

gem 'rails', '3.0.20'
gem 'passenger', '5.0.21'
gem 'delayed_job_active_record', '4.1.1'
gem 'delayed_job', '4.1.2'
gem 'foreman', '0.83.0'

I see the following in the Delayed Job log:

[Worker(host:ubuntu pid:9912)] Starting job worker
[Worker(host:ubuntu pid:9912)] Job MailerJob (id=1720) RUNNING
[Worker(host:ubuntu pid:9912)] Job MailerJob (id=1720) FAILED (0 prior attempts) with StandardError: StandardError
[Worker(host:ubuntu pid:9912)] 1 jobs processed at 12.9574 j/s, 1 failed

I never see the error callback happen. However, if I kill the rails server with CTRL+C then it instantly prints the error callback puts statement.

Why do the error callbacks on the custom Delayed Job not execute while the server is running?

Rails how create a fallback without carrierwave or other upload gem?

I'm trying to create a fallback helper for a object but on the page just shows the image broken link and the assets url. so, know how?

def display_image(pdata)  
    unless pdata.nil? 
      image_tag(pdata.image) 
    else
      image_tag("/assets/fallback/small_foto.png")
     end    
end

rails 3 link_to not working - no route matches

I am working on a rails 3 app. I am trying to make a simple link_to block, but I keep getting a routing error. I am not used to rails 3 (only have used rails 4), and am wondering if I am just missing something dumb, or if this is a rails version thing.

Here are my routes

namespace :api do 
  resources :multiple_prospects, :only => [:update, :destroy] do
    put :flag,          :on => :member
    put :mass_flagging, :on => :collection
    put :mass_archived, :on => :collection
    put :mass_updating, :on => :collection
  end
end

the controller looks like this

class Api::MultipleProspects < ApiController

  def update
  end

  def flag
  end

  def destroy
  end
end

and here is the link_to that is resulting in the error: No route matches {:action=>"flag", :controller=>"api/multiple_prospects"}

<%= link_to flag_api_multiple_prospect_path do %>
   <button><i class="icon icon-flag prospect-flag"></i></button>
 <% end %>

and the output of rake routes CONTROLLER=api/multiple_prospects is

 flag_api_multiple_prospect PUT    /api/multiple_prospects/:id/flag(.:format)      api/multiple_prospects#flag
mass_flagging_api_multiple_prospects PUT    /api/multiple_prospects/mass_flagging(.:format) api/multiple_prospects#mass_flagging
mass_archived_api_multiple_prospects PUT    /api/multiple_prospects/mass_archived(.:format) api/multiple_prospects#mass_archived
mass_updating_api_multiple_prospects PUT    /api/multiple_prospects/mass_updating(.:format) api/multiple_prospects#mass_updating
               api_multiple_prospect PUT    /api/multiple_prospects/:id(.:format)           api/multiple_prospects#update
                                     DELETE /api/multiple_prospects/:id(.:format)           api/multiple_prospects#destroy

does anyone see something wrong I am doing? I have done something like this in rails 4 and it worked fine. I am not sure what I am doing wrong here that is causing this error. Any help would be much appreciated.

Rails has_many through with where condition

I have the following associations in my Survey model:

has_many :survey_group_lists, -> { order 'sequence ASC, group_id ASC' }
has_many :groups, through: :survey_group_lists

I want to add where cluase to :groups association so it will return only active groups. I've tried something like this:

has_many :groups, -> { where(active: true) }, through: :survey_group_lists

but it returns me an error:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "slide_groups"

What I'm doing wrong?

SignatureDoesNotMatch Error while downloading file using X-Accel-Redirect

There are several questions related to this but this use case is slightlt different.

In Rails - In my controller I set response header explicitly :

   response.headers['X-Accel-Redirect'] = "some_url"

Nginx Config

   location ~* ^/some_url/(.*){     

            set $s3_bucket        '$arg_bucket_name';
            set $aws_access_key   'AWSAccessKeyId=$arg_AWSAccessKeyId';
            set $url_expires      'Expires=$arg_Expires';
            set $url_signature    'Signature=$arg_Signature';
            set $url_full         '$1?$aws_access_key&$url_expires&$url_signature';
            proxy_hide_header Content-Disposition;
            add_header Content-Disposition 'attachment; filename=$arg_filename';
            proxy_hide_header      x-amz-id-2;
            proxy_hide_header      x-amz-request-id;
            proxy_buffering        off;
            proxy_intercept_errors on;
            resolver               4.2.2.2 8.8.8.8 valid=300s;
            proxy_pass             https://$s3_bucket/$url_full;
}

Using this to download 100 of files through nginx ,in few cases I am getting error

          SignatureDoesNotMatch

          The request signature we calculated does not match with the signature you provide.