vendredi 14 août 2015

i get error omniauth: (stripe_connect) Authentication failure! invalid_credentials: OAuth2::Error, invalid_client: No such API key: Bearer

i tested my app locally and works fine, but then i deployed it to Heroku and no im running into issues. i get this error after i skip the form for redirection: ERROR -- omniauth: (stripe_connect) Authentication failure! invalid_credentials: OAuth2::Error,

This is what my files look like

using gem figaro for handling the keys.

application.yml:

STRIPE_SECRET: sk_test_*************** STRIPE_CONNECT_CLIENT_ID: ca_**************

omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do provider :stripe_connect, ENV['STRIPE_CONNECT_CLIENT_ID'], ENV['STRIPE_SECRET'] end

secrets.yml:

STRIPE_SECRET: sk_test_*************** STRIPE_CONNECT_CLIENT_ID: ca_**************



via Chebli Mohamed

Compare sql VS active record requests with Benchmark-ips

I'm trying to compare active record request with sql request in my rails project. I'm using Benchmark-ips and pry.

Here what's happen :

[4] pry(main)> Benchmark.ips do |x|
[4] pry(main)*   x.report("sql request") { User.where("EXISTS (SELECT 1 FROM groups_users WHERE groups_users.user_id = users.id AND groups_users.group_id IN (?))", [8939, 8950]).where("NOT EXISTS (SELECT 1 FROM groups_users WHERE groups_users.user_id = users.id AND groups_users.group_id IN (?))", [8942]).ids }
[4] pry(main)*   x.report("active record") { (User.joins(:groups).where(groups: {id: ["8939","8950"]}) - User.joins(:groups).where(groups: {id: 8942})).map(&:id) }
[4] pry(main)*   x.compare!
[4] pry(main)* end
Calculating -------------------------------------
         sql requestNameError: uninitialized constant User
from (pry):15:in `block (2 levels) in __pry__'

I did the same with the classic benchmark tool.

[65] pry(main)> Benchmark.bm do |x|
[65] pry(main)*   x.report("sql request") { User.where("EXISTS (SELECT 1 FROM groups_users WHERE groups_users.user_id = users.id AND groups_users.group_id IN (?))", [8939, 8950]).where("NOT EXISTS (SELECT 1 FROM groups_users WHERE groups_users.user_id = users.id AND groups_users.group_id IN (?))", [8942]).ids }
[65] pry(main)*   x.report("active record") { (User.joins(:groups).where(groups: {id: ["8939","8950"]}) - User.joins(:groups).where(groups: {id: 8942})).map(&:id) }
[65] pry(main)* end
       user     system      total        real
sql request   (1.5ms)  SELECT "users"."id" FROM "users" WHERE (EXISTS (SELECT 1 FROM groups_users WHERE groups_users.user_id = users.id AND groups_users.group_id IN (8939,8950))) AND (NOT EXISTS (SELECT 1 FROM groups_users WHERE groups_users.user_id = users.id AND groups_users.group_id IN (8942)))
  0.010000   0.010000   0.020000 (  0.027799)
active record  User Load (9.4ms)  SELECT "users".* FROM "users" INNER JOIN "groups_users" ON "groups_users"."user_id" = "users"."id" INNER JOIN "groups" ON "groups"."id" = "groups_users"."group_id" WHERE "groups"."id" IN (8939, 8950)
  User Load (0.8ms)  SELECT "users".* FROM "users" INNER JOIN "groups_users" ON "groups_users"."user_id" = "users"."id" INNER JOIN "groups" ON "groups"."id" = "groups_users"."group_id" WHERE "groups"."id" = $1  [["id", 8942]]
  0.050000   0.000000   0.050000 (  0.074597)
=> [#<Benchmark::Tms:0x007ff477ce7c28 @cstime=0.0, @cutime=0.0, @label="sql request", @real=0.02779875499982154, @stime=0.010000000000000009, @total=0.02000000000000024, @utime=0.010000000000000231>,
 #<Benchmark::Tms:0x007ff473f3f7e0 @cstime=0.0, @cutime=0.0, @label="active record", @real=0.07459704099892406, @stime=0.0, @total=0.04999999999999982, @utime=0.04999999999999982>]



via Chebli Mohamed

restoring bundle path to default after accidentally erasing it

I'm running a Mac, using Terminal, working with Ruby on Rails.

I was trying to figure out where bundle install gemfiles on my machine. So I ran the command

bundle --path

and now it appears my machine does not know where any of my gem files are located. How do I restore it to it's original functionality?

Here is the error...

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

/Users/theDanOtto/.rvm/rubies/ruby-2.1.2/bin/ruby extconf.rb
/Users/theDanOtto/.rvm/rubies/ruby-2.1.2/bin/ruby: invalid option -D  (-h will show valid options) (RuntimeError)

extconf failed, exit code 1

Gem files will remain installed in /Users/theDanOtto/Dropbox/Sites/Current Development/ClashOfClanV2/path/ruby/2.1.0/gems/json-1.8.3 for inspection.



via Chebli Mohamed

Rails Migration: How to increase INTEGER size by using ROR migration

My contacts table number column is Integer type. Now I am planning to increase the limit.

Any one please let me know how can we increase limit by using ROR migration.



via Chebli Mohamed

Undefined method `name' for nil:NilClass for search form

I am creating search form, and I have created search controller and other controller named as user. Here is the code of search_controller

def search
  if params[:q]
    @users = User.q(params[:q]).order("created_at DESC").paginate(page: params[:page])
  else
    @users = User.all.order('created_at DESC').paginate(page: params[:page])
  end
end

Here is the search form

<%= form_tag search_path, :method => 'get' do %>
  <%= text_field_tag :q, params[:q] %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

But when I search I am getting undefined method 'name' for nil:NilClass error.

class UsersController < ApplicationController
  before_action :logged_in_user, only: [:index, :edit, :destroy] 

  def index
    @users = User.paginate(page: params[:page])
  end

  def show
    @user = User.find(params[:id])
    @archings = @user.archings.paginate(page: params[:page])
  end

  def new
    @user = User.new
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted"
    redirect_to users_url
  end

  def create
    @user = User.new(user_params)
    if @user.save
      log_in @user
      flash[:success] = "Welcome to the Arch"
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                   :password_confirmation)
    end

   def logged_in_user
      unless logged_in?
    store_location
        flash[:danger] = "Please log in."
        redirect_to login_url
      end

 end
end

Can anyone tell me where I am doing mistake?

PS: I am beginner and new to rails and ruby.



via Chebli Mohamed

Paperclip plugin restrict image upload types also allow image to be null. Rails

In my Rails 2 application, images for products are uploaded using Paperclip as a plugin. I need to restrict the image types to jpeg and png and also allow saving of product even if image is not uploaded.

The current code is

has_attached_file :master_image,
  :url  => "/images/products/:id/private/master.img",
  :path => ":rails_root/public/images/products/:id/private/master.img"

validates_attachment_content_type :master_image, :content_type => ['image/png', 'image/jpg'] , :message => "image must be jpg or png." , :allow_nil => true

I added :allow_nil => true but it is not working.

I am getting image must be jpg or png when trying to save without image.

Any help????



via Chebli Mohamed

Fetch bookmark from the database on the basis of tag

I am new in Rails, I have 3 models in the application namely Bookmark, Tag, Tagging. I want to fetch all the bookmark on the basis of tag. I have written the sql queries but i don't know how to implement these in rails.

Attributes of the model are:

Bookmark: id , name

Tag : id , name

Tagging : bookmark_id , tag_id

SQL Queries that i have written for that is :

select * from Bookmark where id = (select bookmark_id from tagging where tag_id = (select * from tag where name= 'tag1'))



via Chebli Mohamed

I have seem this question posted before but the normal "add :content to model" doesn't work for my situation. I have already added it and the error still occurs.

This a modified version of a codecademy project if it looks familiar.

Model

 class CreateNotes < ActiveRecord::Migration
    def change
      create_table :notes do |t|
        t.text :content
        t.timestamps
      end
    end
 end

Controller

class NotesController < ApplicationController
    def index
       @notes = Note.all
    end

    def new
       @note = Note.new
    end

    def create
       @note = Note.new(note_params)
           if @note.save
               redirect_to '/notes'
           else
               render 'new'
           end
    end

    private
    def note_params
       params.require(:note).permit(:content)
    end
end

Route

Rails.application.routes.draw do

     root 'notes#index'
     get "notes" => "notes#index"
     get "notes/new" => "notes#new"
     post "notes" => "notes#create"

index.html.erb

<div class="header">
  <div class="container">
    <h1>Notes</h1>
  </div>
</div>

<div class="notes">
  <div class="container">

    <% @notes.each do |note| %>
        <div class="note">
        <p class="content"><%= note.content %></p>
        <p class="time"><%= note.created_at %></p>
        </div>
    <% end %>
    <%= link_to 'New Note', "notes/new" %>

  </div>
</div>

new.html.erb

<div class="header">
  <div class="container">
    <h1>Notes</h1>
  </div>
</div>

<div class="create">
  <div class="container">

    <%= form_for(@note) do |f| %>
        <div class="field">
            <%= f.label :note %><br>
            <%= f.text_area :content %>
        </div>
        <div class="actions">
            <%= f.submit "Create" %>
        </div>
        <% end %>
  </div>
</div>

If anyone can figure out why I am still getting this error after :content is already in the model, that would be awesome!

P.S. First post so sorry if it is terrible.



via Chebli Mohamed

Progress bar update width when page load?

When I load a page, I want to show a progress bar in a table field, like this:

<% @beacons.each do |beacon| %>
...
    <td><div id="progressbar" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="10"
      aria-valuemin="0" aria-valuemax="100" style="width:100%" ><%= beacon.power %>%</div></td>

but I can not beacon.power to update the width in progress bar, I don't need real time refresh, I just want when I load this page, the progress bar's width can use my db data: beacon.power to desplay

my website is

IP/beacons

my controller:

  def index
    @beacons = Beacon.all

    respond_to do |format|
      format.html { @beacons }
      format.json { @beacons }
    end
  end

I try to use javascript:

$(document).ready(function() {
    $.get("beacons.json", function(data){
      $("#progressbar").css('width', data.power+'%')
    }
    });
});

and it doesn't work , what wrong with my setting?



via Chebli Mohamed

Devise, lockable does not reset failed_attempts after unlocking

I have model Person which uses Devise it has :lockable

I have added these fields in my model:

field :failed_attempts, type: Integer, default: 0
field :locked_at,       type: Time

In my config/initializers/devise.rb file I have that kind of settings:

config.lock_strategy = :failed_attempts
config.unlock_strategy = :time
config.maximum_attempts = 10
config.unlock_in = 30.minutes

I get password and make validation:

if person.valid_password?(params[:password])

   # do something if password is right
else

   person.failed_attempts += 1
   person.save

   if person.failed_attempts >= person.class.maximum_attempts
      person.lock_access!
      PersonMailer.blocked_email(person).deliver_later
   end

end

If password is wrong I increment failed_attemps and then check if it more than maximum attempts. I it is, it will call lock_access! method.

Then I check if lock time is expired or not:

if person.access_locked?
   if person.locked_at && person.locked_at < person.class.unlock_in.ago
     person.unlock_access!
   else
     error!('Access is locked', 401)
   end
 end

If time of blocking is expired, it calls unlock_access! method.

Now here is the problem. When unlcock_access! is called it makes access_locked? false, but does not reset locked_at and failed_attempts values.

What did I miss?



via Chebli Mohamed

Rails 4.2.3 Active Admin error

Im on Windows 7 running Rails 4.2.3 and I have been trying to install active admin as part of an older tutorial.

I updated my Gemfile

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use sqlite3 as the database for Active Record
#gem 'sqlite3'


gem 'pg'
gem 'activeadmin', github: 'activeadmin'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See http://ift.tt/1D4cmMg for more supported runtimes
# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails' 

.........etc

Ran

$bundle install

then

$rails g active_admin:install --skip-users

$ rake db:migrate

restarted my server going to localhost:3000/admin throws this error:

ExecJS::ProgramError in Admin::Dashboard#index

Showing C:/Ruby21-x64/lib/ruby/gems/2.1.0/bundler/gems/activeadmin-3254f53b4b35/app/views/active_admin/page/index.html.arb where line #2 raised:

TypeError: Object doesn't support this property or method

//

I feel like i've followed all the documents on how to install this and have run out of things to read. Is there just some beginner's error here or am I missing something?

as requested here is the code from the index.html.arb file for the gem which is only one line....

insert_tag active_admin_application.view_factory["page"]



via Chebli Mohamed

jeudi 13 août 2015

Custom constraints - postgres

So this is more of a conceptual doubt. Is their any way in which we can apply a constraint that value of that field can't be blank. I know NOT NULL can be used. But I want to check if the field has just spaces, it rejects that value also. For example " " should be rejected.



via Chebli Mohamed

Rails 4.Combine 2 arrays

I have 2 arrays and i want to combine them in one which have to return nested JSON. The first one is cleaner which returns

{
  "response": [
    {
      "id": 1,
      "first_name": "Fernando",
      "last_name": "Gomez",
      "avg_rating": "4.5"
    }  
  ]
}

The second one is reviews from the clients which return the name of the client,comment and rating:

{
  "response": [
    {
      "id": 1,
      "score": 4,
      "comment": "Comment",
      "first_name": "John Doe"
    }
  ]
}

So i try to zip them and loop over each of them here is my code:

cleaners.zip(reviews).each do |cleaner, review|
  if cleaner.id == review.id
   test['first_name'] = cleaner.first_name
   test['last_name'] = cleaner.last_name
   test['rating'] = review.score
   test['comment'] = review.comment
   test['client_name'] = review.first_name
  end
end

When i return my result is:

{
  "response": {
    "first_name": "Fernando",
    "last_name": "Gomez",
    "rating": 4,
    "comment": "Comment",
    "client_name": "John Doe"
  }
}

But my result have to be nested cuz some of the cleaners will have many reviews.It have to be something like this:

{
  "response": {
    "first_name": "Fernando",
    "last_name": "Gomez",
    "score_from_client": [
                {
                  "rating": 4,
                  "comment": "Comment",
                 "client_name": "John Doe"
                }
                ]
  }
}



via Chebli Mohamed

Rails nested form not rendering

I'm guessing this is more of a fundamental issue than the form simply "not rendering", but here it goes. I'll try to keep this brief but a fair amount of context may be needed.

I'm making a custom Rolodex app and the organization gave me specific things to include. For this specific problem I'm dealing with contact emails only. Ideally I would have a system like Google Contact's, where you can click to add another email field and there's a dropdown to select a category (Home, Work, etc.).

In this case the categories are coming from a table called categories. Here is a link to the entity relationship diagram I made for the entire project (not just emails): http://ift.tt/1UGLhWe

To sum things up: How do I set things up to allow the entry of emails during a contact creation/edit?

Here's my relevant code:

models/contact.rb

class Contact < ActiveRecord::Base
  has_many :emails

  accepts_nested_attributes_for :emails
end

models/email.rb

class Email < ActiveRecord::Base
  belongs_to :contact
  belongs_to :category
end

controllers/contacts_controller.rb

# GET /contacts/new
  def new
    @contact = Contact.new
    @email = @contact.emails.build(params[:email])
  end

views/contacts/_form.html.erb

<%= form_for(@contact) do |f| %>

    #Other contact fields here

    <% f.fields_for @email do |email| %>
        <div class="field">
          <%= email.label :category_id %><br>
          <%= email.text_field :category_id %><br/>
        </div>
        <div class="field">
          <%= email.label :email %><br>
          <%= email.text_field :email %><br/>
        </div>
    <% end %>
    <div class="actions">
      <%= f.submit %>
    </div>
<% end %>

I also confirmed that this whole setup works "manually". I can make contacts and categories, and then properly reference them when creating a new email by manually putting in the foreign ids. The issue here is a matter of condensing this process into one form.

Any input would be appreciated, thanks!



via Chebli Mohamed

Ruby form_for html attributes not working, multipart or id

I am desperately trying to put a multipart to my form in Ruby but it won't show up. I looked up online everywhere but whatever I try it doesn't show. Even simple IDs or classes won't work...

Is there any dependency I am not aware of?

<%= form_for @listing, :html => {:id => "account_form", :multipart => true } do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <%= f.label :title %>
      <%= f.text_field :title, class: 'form-control' %>

      <%= f.label :highlights %>
      <%= f.text_area :highlights, class: 'form-control' %>

      <%= f.label :location %>
      <%= f.text_area :location, class: 'form-control' %>

      <%= f.label :catering %>
      <%= f.text_area :catering, class: 'form-control' %>

      <%= f.label :travel %>
      <%= f.text_area :travel, class: 'form-control' %>

      <%= f.label :dates %>
      <%= f.text_area :dates, class: 'form-control' %>

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

      <%= f.label :category %>
      <%= f.select :category, options_from_collection_for_select(Category.all, :id, :name), :include_blank => true %>

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

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

      <%= f.label :photo %>
      <%= f.file_field :photo %>

  <%= f.submit "Post", class: "btn btn-primary" %>
<% end %>

which will result in the following HTML

<form class="new_listing" id="new_listing" action="/listings" accept-charset="UTF-8" method="post">

Please help!



via Chebli Mohamed

Rails Validation Failed -- want to stay on form

I have a form in which I am trying to validate that date_to is not less than date_from. The validation seems to be recognized because when I submit a form with date_to less than date_from I get the following error:

Validation failed: Start date must be before end date

However I don't want validation to break the page.

Goal:

If validation fails stay on form page and display a message at the top describing the error.

Model:

validate :validate_date_from_before_date_to, :on => [:create, :edit, :update]

def validate_date_from_before_date_to
  if self.date_from && self.date_to
  errors.add(:end_date, "Start date must be before end date") if self.date_to < self.date_from
end

end

Controller:

if @project.save! == false
  redirect_to edit_admin_project(@project)
else
  redirect_to admin_project_path(id: params[:id])
end

I have checked the similar questions and even one identical one, unfortunately without luck.

Any and all help is greatly appreciated. Thank you!



via Chebli Mohamed

Pass ID of parent to new association - rails

Trying to pass the ID from the Edit action view

on the form I have

   <h1>Editing Video</h1>

<%= render 'form' %>

<br>
<%= link_to 'New Poster', new_poster_path %> | 
<%= link_to 'Show', @video %> |
<%= link_to 'Back', videos_path %>

While the user is on the edit form for video I want them to be able to edit the posters that belong to the video (has_many :posters)

On the Edit action of the video controller I added

@poster = Poster.new

when the user clicks the new poster link they are directed to the new poster and can upload an image

when I create the record - it doesn't pass the ID of the video.

I have in my model for the posters

belongs_to :video

so I don't know how I am safely supposed to pass the ID of the video edit I was on to the newly created poster.

table Posters id poster_url video_id <-- this should have the id of the video I was just editing...

Routes:

 Rails.application.routes.draw do
      resources :posters
      resources :people

      resources :profiles
      devise_for :users

      resources :videos do
        resources :posters
      end

      # The priority is based upon order of creation: first created -> highest priority.
      # See how all your routes lay out with "rake routes".

      # You can have the root of your site routed with "root"
       root 'home#index'



via Chebli Mohamed

Rails duplicate of same form in view leaves fields empty

I have a view associated with one model but there are multiple versions of the same form that are hidden until a jquery function shows them. When I try to submit one, all the fields are empty.

Here is the view in question:

= form_for @rfi do |f|
    - if @rfi.errors.any?
      #error_explanation
        h2 = "#{pluralize(@rfi.errors.count, "error")} prohibited this rfi from being saved:"
        ul
          - @rfi.errors.full_messages.each do |message|
            li = message

    .field
      = f.label :svg_ref, "SVG PO Number"
      = f.text_field :svg_ref

    .field
      = f.label :vendor_ref, "Vendor SO Number"
      = f.text_field :vendor_ref

    .field
      = f.label :due
      = f.text_field :due
      = f.hidden_field :rfi_type, value:"order"
    .actions 
      = f.submit



.rfi_type.rfi_type_quote
  = form_for @rfi do |f|
    - if @rfi.errors.any?
      #error_explanation
        h2 = "#{pluralize(@rfi.errors.count, "error")} prohibited this rfi from being saved:"
        ul
          - @rfi.errors.full_messages.each do |message|
            li = message

    .field
      = f.label :reference, "Quote number"
      = f.text_field :reference
      = f.hidden_field :rfi_type, value:"quote"
    .field
      = f.label :due
      = f.text_field :due
    .actions 
      = f.submit

This is the Jquery involved

$ ->
    $(".rfi_type").hide()
    $(".rfi_type_order").show()


    $("input:radio[name=rfi_type]").change ->
        $(".rfi_type").hide()
        $(".rfi_type_"+$(this).val()).show()
        return
    return



via Chebli Mohamed

Ruby on Rails link middle click

I have multiple links in my project for example:

_index.html.erb:

<%= link_to('New Project', new_project_path, :remote => true) if Project.create_authorized? %>

controller:

def new
  @project = Account.root_account.nil? ? Project.new : Account.root_account.projects.new
end

new.js.erb:

$("#right-panel").html("<%= escape_javascript(render(:partial => 'projects/form', :locals => {:project => @project}) ) -%>");

My problem is that when I am doing mouse middle click(I mean, I want to open a new tab) on the link then it raises a error as:

Template is missing Missing template projects/new, application/new with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :arb]}. Searched in: * "/home/raj/workspace/papayaheaderlabs.banana/app/views" * "/home/raj/.rvm/gems/ruby-2.0.0-p598@banana/gems/doorkeeper-2.2.1/app/views" * "/home/raj/.rvm/gems/ruby-2.0.0-p598@banana/bundler/gems/activeadmin-655e2be7a351/app/views" * "/home/raj/.rvm/gems/ruby-2.0.0-p598@banana/gems/kaminari-0.16.3/app/views"

Plese help how to solve this issue



via Chebli Mohamed

To display default user image if image is not present (ruby on rails)

I want to write a condition in ruby to display default image if no user image is present , if present display the present image.

please help.

This is my view page:

                 `@product.reviews.each do |r|
                  a href="#"
                    = image_tag r.user.image_url :thumbnail`



via Chebli Mohamed