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

Rails Devise & Simple Form

I am trying to make an app with Rails 4, devise and simple form.

The devise view has a standard remember me checkbox, which I am trying to format.

I read a blog post showing me how to alter the devise checkbox aligment for the remember me field (which as a standard pushes the checkbox to the left of the vertical alignment of the other fields in the form.

To fix this, I changed my framework_and_overrides.css.scss to include:

.checkbox input[type="checkbox"] {
  margin-left: 0;
}

Now, when I try to use the devise form, the checkbox appears on top of the letter 'R' in the remember me label.

Also, my css to style the words 'remember me' won't apply to that text.

My field currently has:

        <%= f.input :remember_me,  as: :boolean,  inline_label: true, :input_html => {:class => 'deviselabels'}, label: false if devise_mapping.rememberable? %>

The styling I'm trying to apply is in the 'devise labels' class - it changes the font color and size. But it isn't working on this specific form element. It works fine on the other elements in the form and doesnt alter margins:

.deviselinks {
  font-family: 'Quicksand', sans-serif;
  color: white;
    a:link {text-decoration:none; background-color:transparent; color:white;};
    a:visited {text-decoration:none;background-color:transparent; color:white;};
    a:hover {text-decoration:none;background-color:transparent; color:white;};
    a:active {text-decoration:none;background-color:transparent; color:white;};

}

Does anyone know how to move the words 'remember me' over so they are to the left of the check box (rather than the 'R' being underneath the checkbox)? Also, how do I apply my font styling to the words 'Remember me'?



via Chebli Mohamed

ASCII and newlines

Here's a string:

"Hello\r\nHow are you?"

I saved this string into my DB two ways:
1) by copying this exact string into the console then saving;
2) by typing it (with an actual newline rather than \r\n) into the object's form and submitting it.

Both results return the above string on the console. Both are encoded in UTF-8.

However, only the first responds to .ascii_only? with true.

  1. Why is this the case? How can I save the above string as ascii_only with method #1?
  2. How can I convert method #1's string to ascii_only??


via Chebli Mohamed

Dynamic query builder similar to http://ift.tt/1h8GQoX with rails

i have created dynamic query builder with rails using angular query builder . I am facing issue with retrieving value on edit page as i am getting nested json .Does anyone implemented the same or similar feature ?



via Chebli Mohamed

Faye Websocket Error Rails 2.2.2 (production)

I have been using Faye on 2.1.3 with no problems, but upon upgrading to 2.2.2 I can only get local instance to work. Production websockets fail. I replaced the actual server name with blahblahserver.com

Faye Rackup

require 'faye'
app = Faye::RackAdapter.new(:mount => '/faye', :timeout => 25)
Faye::WebSocket.load_adapter('thin')
run app

Application.html.erb

<%= javascript_include_tag "application",params[:controller],'http://ift.tt/1fbf1dG','data-turbolinks-track' => true %>

Helper (send function)

def broadcast(channel, &block)
  message = {:channel => channel, :data => capture(&block)}
  uri = URI.parse("http://localhost:9292/faye")
  Net::HTTP.post_form(uri, :message => message.to_json)
end

In Rails Controller

gon.env = Rails.env

Listener (Coffeescript)

$ ->
  # required when faye listener is present to keep from having hard env changes
  # parallel gon.env = Rails.env in controller must be present
  server_name = undefined
  switch gon.env
    when "production"
     server_name = 'app-server1.blahblahserver.com'
    when "staging"
     server_name = 'si-staging.blahblahserver.com'
    when "development"
     server_name = 'localhost'
  address = 'http://' + server_name + ':9292/faye'

# Listener for this page locally
faye = new (Faye.Client)(address)
faye.subscribe ('/logs/'+gon.property_id+ '/new'), (data) ->
 if getParameterByName('all_open') == "true"
  window.location.href = window.location.href
 else if  gon.today == gon.display_date
  ready(data)
 else window.location.href = window.location.href
return
faye.subscribe ('/logs/'+gon.property_id+ '/alert'), (data) ->
 console.log('pre-ajax')
 $.ajax 'load_customer_messages' ,
  type: "GET",
  dataType: "JSON",
  asnyc: false,
  success: (data2) ->
    $('#ajax').click()
 return
return

ready = (data) ->
 eval data 



via Chebli Mohamed

Share custom Image, Url, Content on Facebook, Twitter, Google plus For Different products

I have a site that have different products . for each product details page I want button for facebook, google plus and twitter . That should share image , url , description of that product.

I googled for custom sharing and tried different codes found from different documentation, but in vain.

Thanks in advance.



via Chebli Mohamed

Ruby Pundit Authorization Users and Collaborators

Ruby beginner over here. I'm currently working on a project where Users can create public and private wikis. There are three different roles: Admin, Standard User and Premium User. A Standard user can only see public wikis.

Authorization is working properly via Pundit, I've successfully been able to list the wikis I want each user to have access to, but I'm missing one thing: Wikis to which the Standard user has been added as a collaborator.

Collaborator is not a role, so I'm having difficulty adding those wikis to the index (Wiki has many users through collaborators).

If you have any ideas on how I can implement this, or perhaps an alternative route, I'd be happy to hear them.

Currently, a standard user can access only public wikis and wikis he or she has created (which are public by default). Currently, the Standard user can view and edit a private wiki he or she has been added to but only by visiting the direct wiki url.

This is what my code looks like so far:

wiki.rb

class Wiki < ActiveRecord::Base
  belongs_to :user
  has_many :collaborators
  has_many :users, through: :collaborators

  scope :visible_to, -> (user) { user && (user.premium? || user.admin?) ? all : where(public: true)  }
  scope :publicly_visible, -> {where(public: true)}
end

wiki_policy.rb

class WikiPolicy < ApplicationPolicy
  def index?
    true
  end

  def show?
    record.public? || user.present? && (record.user == user || user.admin? || user.premium? || record.users.include?(user))
  end

  def create?
    user.present? 
  end

  def new?
    create?
  end

  def update?
    user.present? && (record.user == user || user.admin? || record.users.include?(user))
  end

  def destroy?
    update?
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      if @user.present?
        wikis = Wiki.visible_to(@user)
      else
        wikis = Wiki.publicly_visible
      end
    end
  end
end

wikis_controller.rb

class WikisController < ApplicationController
  def index
    @wikis = policy_scope(Wiki).paginate(page: params[:page], per_page: 10)
    authorize @wikis 
  end
...
end



via Chebli Mohamed

Resque not recognising instance variables

I am using resque to send emails. The emails do not send if my mailer template contains any references to instance variables.

users_controller.rb

def create
  @user = User.new(user_params)
  if @user.save
    Resque.enqueue(SendActivationEmail, @user.id)
    flash[:info] = "Please check your email to activate your account."
    redirect_to root_url
  else
    render 'new'
  end
end

send_activation_email.rb

class SendActivationEmail
  @queue = :email_queue
  def self.perform(user_id)
    user = User.find(user_id)
    UserMailer.account_activation(user).deliver_now
  end
end

user_mailer.rb

class UserMailer < ApplicationMailer
  def account_activation(user)
    @new_user = user
    mail to: user.email, subject: "Account activation"
  end
end

account_activation.text.erb

Hi,

Welcome. Click on the link below to activate your account:

<%= edit_account_activation_url(@new_user.activation_token, email: @new_user.email) %>

The error recorded in resque web is: No route matches {:action=>"edit", :controller=>"account_activations", :email=>"user5@domain.com", :id=>nil} missing required keys: [:id]

The following will send when the link is removed...

account_activation.text.erb

Hi,

Welcome. Click on the link below to activate your account:



via Chebli Mohamed

rails 4 radio_button_tag default not selected

I'm using Rails 4 but I can't get the radio_button_tag to set the first option as default.

.field
  =radio_button_tag :type, "order", checked:"true", class: "rfi_radio"
  =label_tag :type_order, "Information pertaining to an order"
  br
  =radio_button_tag :type, "quote", class: "rfi_radio"
  =label_tag :type_quote, "Information pertaining to a quote"
  br
  =radio_button_tag :type, "customer", class: "rfi_radio"
  =label_tag :type_customer, "Information pertaining to a customer"
  br
  =radio_button_tag :type, "general", class: "rfi_radio"
  =label_tag :type_general, "General information"



via Chebli Mohamed

Why is my Rails Controller expecting JSON from the format.js call?

I'm adding a new Sale_Contact to my Rails app using a Bootstrap 3 modal and AJAX. It isn't working - I'm getting a 200 OK code returned from the server, and the Object is being added to the database, but because there is no JSON returned (the create action just sends back the create.js.erb file to the JQuery.parse.json action) then I'm firing ajaxError rather than ajaxSuccess, my modal isn't closing and the javascript to update the view with the new sale_contact object is not executed.

I can't work out why my Rails controller is expecting a Json object returned in this instance - I've basically copied this code directly from other objects I also build with modals and AJAX, which all work perfectly. Can anyone help me understand what's going wrong in this instance?

My Controller:

  def create
   @sale_contact = SaleContact.new(sale_contact_params)
   @sales_opportunity = @sale_contact.sales_opportunity

respond_to do |format|
  if @sale_contact.save
    #format.html { redirect_to @sale_contact.sales_opportunity, notice: 'Sale contact was successfully created.' }
    format.js 
    #format.json { render json :show, status: :created, location: @sale_contact }
  else
    format.html { render :new }
    format.json { render json: @sale_contact.errors, status: :unprocessable_entity }
    format.js { render json: @sale_contact.errors, status: :unprocessable_entity }
  end
 end
end

I've tested this, and I can see that the if @sale_contact.save block is being run. As you can see above I've also commented out the format.html and format.json lines but this doesn't change the outcome.

My create.js.erb file for Sale_Contacts:

    console.log('anything at all');
    //update the selection list with the new sale contact, and close the modal
    $('#sales_opp_sale_contact_modal').modal('hide')
                    .clear_previous_errors();
    resetForm($('#new_sale_contact'));
    $input = $('#contact_error');
    $input.closest('.form-group').removeClass('has-error').find('.warning-block').html('');
  //render the newly added sale contact to the table if the AJAX call succeeded
   console.log('fired');
   $(document).ajaxSuccess(function() {
    $( ".log" ).text( "Triggered ajaxSuccess handler. The ajax response was: " +
  xhr.responseText );
    $('#sales-opp-key-contacts-table-div').html("<%= escape_javascript(render :partial => 'sale_contacts/table')%>");
    //console.log(document);
    $('.alert').remove();
    $('.navbar-default .navbar-nav > li > a').removeClass('selected');
    $('#sale-contacts').DataTable({
        retrieve: true,
});

This code is never fired - instead this is passed back to the ajaxError function:

Uncaught SyntaxError: Unexpected token c
jQuery.parseJSON @ jquery.js?body=1:8483
(anonymous function) @ organizations.js?body=1:23
jQuery.event.dispatch @ jquery.js?body=1:4642
jQuery.event.add.elemData.handle @ jquery.js?body=1:4310
jQuery.event.trigger @ jquery.js?body=1:4551
done @ jquery.js?body=1:9286
jQuery.ajaxTransport.send.callback @ jquery.js?body=1:9686

As you can see, the "c" character that starts my create.js.erb file is passed in, which isn't valid JSON, and therefore the parseError is thrown.

I've added some new code to look at the returned items from the ajaxError - in case these help:

$(document).ready(function(){
 $(document).on('ajaxError', function(XMLHttpRequest, textStatus, errorThrown){
 console.log("some error" + errorThrown);
 });
 $(document).on('ajaxError', function(req, xhr, err){ 
  console.log('my message' + err + xhr.status);
 });
 $(document).bind('ajaxError', function(event, jqxhr, settings, exception){

// note: jqxhr.responseJSON undefined, parsing responseText instead
console.log(jqxhr.responseText)
$(event.data).render_form_errors( $.parseJSON(jqxhr.responseText) );
});

The output from this is:

some error[object Object]
my message[object Object]200
console.log('anything at all');
//update the selection list with the new sale contact, and close the modal
$('#sales_opp_sale_contact_modal').modal('hide')
                    .clear_previous_errors();
resetForm($('#new_sale_contact')); .....

I've edited this for brevity, you can see the first two responses show that I'm sending back objects (how do I find out which?) and the 200 OK code, and the responseText is the create.js.erb file that doesn't get fired.

I'm going crazy trying to work out why this is not working. The only difference between this object and the other objects I'm creating in this way is that my Sale_Contact is a join table (it belongs_to both Sales_Opportunities and Key_Contacts so they have_many_through this table).

In case it matters, here's the model:

class SaleContact < ActiveRecord::Base
 validates :key_contact_id, presence: true
 validates :sales_opportunity_id, presence: true
 belongs_to :key_contact
 belongs_to :sales_opportunity
 enum role: [ :not_known, :evaluator, :decision_maker, :budget_holder ]
 enum preference: [ :unknown, :supporter, :enemy ]
end

And here's my sale_contacts/show.json.jbuilder file:

json.extract! @sale_contact, :id, :key_contact_id, :sales_opportunity_id, :role, :preference, :created_at, :updated_at

Any help would be appreciated

Quick Edit Here's my routes.rb file for the relevant items, I had hoped this might be the issue:

  resources :sales_opportunities do
   resources :timeline_events, shallow: true
   resources :swots, shallow: true
   resources :sale_contacts, shallow: true
 end

Second edit

Just as an idea that came from writing this post, I ran the same ajax analysis for an ajaxSuccess event in my other modals - they also return the exact same info as above:

some error[object Object]
my message[object Object]200
whatever create.js.erb template was added successfully

So it's not the return from the server that's the issue - something else is going wrong. I'm using Bootstrap 3 modals, so maybe I need to dig into their ajax code to find the problem.



via Chebli Mohamed

Rails: Autocreate associated records as soon as parent record is saved

I'm trying to automatically create records in a child table as soon as a parent record is saved but I'm stuck and need a help how to do this.

So my table hierarchy of the Orgs is like Org->Brand->Restaurant (eg. Americana(Org) -> KFC(Brand) ->San Francisco(Restaurant)).

A Brand has many menus and Menu belongs to a Brand. Now I want to cascade menu for each Restaurant from the Brand's menu because I want to be manage price by the Restaurant. In order to do that, I created a 'local_menus' table which contains restaurant_id and menu_id so that I don't have to duplicate some data and changes in the local_menus will not be affected to its parent.

The question is how do I auto create records in 'local_menus' as soon as a parent menu is created. To be more specific, when I create a menuA, the same menu needs to be created automatically for all the restaurants under the brand. Appreciate your support.

MODELS:

class LocalMenu < ActiveRecord::Base
  belongs_to :restaurant
  belongs_to :menu
end

class Menu < ActiveRecord::Base
    has_many :local_menus
    belongs_to :brand
end

class Restaurant < ActiveRecord::Base
    has_many :menus, through: :local_menus
end

TABLES:

local_menus
    t.integer  "restaurant_id",  limit: 4
    t.integer  "menu_id",        limit: 4
    t.boolean  "active_status",    limit: 1
    t.boolean  "instock_status", limit: 1
    t.integer  "price",          limit: 4


menus
    t.integer  "restaurant_id",      limit: 4
    t.string   "name",               limit: 255
    t.integer  "price",              limit: 4
    t.integer  "brand_id",           limit: 4
    t.integer  "category_id",        limit: 4
    t.text     "description",        limit: 65535
    t.boolean  "active_status",      limit: 1
    t.date     "start_date"
    t.date     "end_date"

restaurants
    t.string   "name",          limit: 255
    t.string   "name_kana",     limit: 255
    t.integer  "price",         limit: 4
    t.boolean  "active_status", limit: 1
    t.integer  "brand_id",      limit: 4



via Chebli Mohamed

How to store variables passed to a Ruby class when initializing securely so that they can be accessed by other methods?

I need to know how tosecurely store the parameters passed into a Ruby class when initializing as shown below...

 myclass = MyClass.new(auth_token)

... So that it can be accessed by other methods in the class to perform their actions like this :

myclass.do_something

The parameters that I pass are very sensitive so the security should be the highest priority. How can I achieve this?



via Chebli Mohamed

Redirect queries to a specific server based on the collection (sharding?)

I have two mongodb servers. Would it be possible to specify, based on the collection, on which server the query will be performed?

Preferably, I would like to do this at the application level (Rails + mongoid)

The reason is that I'm migrating some data and have this specific collection that will need to live temporary on a different server on the same vpc.

Thanks



via Chebli Mohamed

How to fix first page with Rails' Turbolinks and Wistia's Fresh Url

When using Wistia's Fresh Url plugin, Turbolinks doesn't work on the first page. For example, if you navigate one page away and click the back button in the browser, the url with change but the page won't actually change at all. Once you navigate two pages away, though, Turbolinks starts working again.



via Chebli Mohamed

Raty Plugin Rendering Stars Twice

As title specifies, I am adding a raty star plugin into one of my form templates (only doing this once) but for some reason, the script injects the stars twice.

    <div id="star-rate" style="cursor: pointer;">
    <img alt="1" src="/assets/star-off.png" title="bad">
    &nbsp;
    <img alt="2" src="/assets/star-off.png" title="poor">
    &nbsp;
    <img alt="3" src="/assets/star-off.png" title="regular">
    &nbsp;
    <img alt="4" src="/assets/star-off.png" title="good">
    &nbsp;
    <img alt="5" src="/assets/star-off.png" title="gorgeous">
    <input name="review[rating]" type="hidden">
    <img alt="1" src="/assets/star-off.png" title="bad">
    &nbsp;
    <img alt="2" src="/assets/star-off.png" title="poor">
    &nbsp; 
    <img alt="3" src="/assets/star-off.png" title="regular">
    &nbsp;
    <img alt="4" src="/assets/star-off.png" title="good">
    &nbsp;
    <img alt="5" src="/assets/star-off.png" title="gorgeous">
    <input name="review[rating]" type="hidden"></div>

I didn't manually type this in and was actually following a tutorial that seemed to have this render properly. Below is the script I am running in the same template I wrote in backbone.

    <div class="form-group">
      <label for="review-rating">Rating: </label>
      <div id="star-rate"></div>
    </div>

    <script>
      $('#star-rate').raty({
      path: '/assets/',
      half: true,
      start: 0,
      scoreName: 'review[rating]'
      });
    </script>

I have seen that this question was posted once before in 2011 but it didn't help me. If anybody has any thoughts on the double rendering issue of raty, please help. I have tried changing the number of stars and the div that surrounds the #star-rating div but it also didn't work.



via Chebli Mohamed

how to show html in rails options_from_collection_for_select

I used rails options_from_collection_for_select for select

options_from_collection_for_select(@tenants, :id, :tenant_text_value, current_tenant.try(:id))```

def tenant_text_value
    "<a href='http://www.google.com'>google</a>".html_safe
  end

I want <option value="215"><a href='http://www.google.com'>google</option> and when I click a and go to google.

however, I just got <option value="215">google</option>

If I use "<a href='http://www.google.com'>google</a>".to_s and I got <option value="215"><a href='http://www.google.com'>google</a></option> just a text not a link.

What should I do ?



via Chebli Mohamed

Rails delayed_job doesn't perform

I've defined two custom jobs. One works and the other does not. The one not working enqueues but nothing else ever happens. No failure or success.

After trying all the tips at collectiveidea where I found the documentation and on SO, I'm stumped. I have job failures being retained. I'm logging all DJ events in a separate log. They provide no clues. My DJ log shows the job being enqueued and that's it.

The job is to post to a web site.

This is what appears in the delayed_job table for the bad job.

2.1.2 :004 > Delayed::Job.last
 => #<Delayed::Backend::ActiveRecord::Job id: 2515456, priority: 0, attempts: 0, handler: "--- !ruby/struct:SendHubCommandJob\ncmd: getOptions...", last_error: nil, run_at: "2015-08-14 02:07:32", locked_at: nil, failed_at: nil, locked_by: nil, queue: nil, created_at: "2015-08-14 02:07:32", updated_at: "2015-08-14 02:07:32">

My custom job:

SendHubCommandJob = Struct.new(:cmd, :hub, :badge, :arg1, :arg2) do
  # Send a command to the hub to forward to badge

  def enqueue(job)
    #called
    Delayed::Worker.logger.info "SendHubCommandJob enqueue: #{cmd} #{hub} #{badge} #{arg1} #{arg2}"
  end

  def success(job)
    #not called
    Delayed::Worker.logger.info "SendHubCommandJob: success"
  end

  def error(job, exception)
    #not called
    Delayed::Worker.logger.info "SendHubCommandJob: error"
    # Send email notification / alert / alarm
  end

  def failure(job)
    #not called
    Delayed::Worker.logger.info "SendHubCommandJob: failure"  
  end

  def perform
    #not called
    Delayed::Worker.logger.info "SendHubCommandJob: got here"
    Delayed::Worker.logger.info "SendHubCommandJob perform: #{:cmd} #{hub} #{badge} #{arg1} #{arg2}"

    require "open-uri"
    require "net/http"

    @@cmd_count = @@cmd_count + 1
    s = "http://#{hub}.local:9090/cmd"
    uri = URI(s)
    req = Net::HTTP::Post.new(uri)
    Delayed::Worker.logger.info "SendHubCommandJob: #{uri}"

    # Set where hub should send asynch response
    response_addr = "mark.local:3000"

    #TODO Implement other commands here
    case @cmd
    when 'getOptions'
      req.set_form_data('type' => 'cmd', 'cmd'=>'READ', 'subcmd'=>'GENERAL', 'datatype'=>'OPTIONS', 'modulename'=>'BTPENDANT', 
      'sensorid'=>'#{@badge}', 'moduleidx'=>'0', 'processtype'=>'1', 'count_or_ms'=>'0', 'trackingid'=>@@cmd_count, 'response_addr'=>response_addr,
      'jsontxt'=>{'device'=>'#{@hub}'})

    when 'setOptions'  #arg1 is 12 byte hex string per badge spec
      req.set_form_data('type' => 'cmd', 'cmd'=>'WRITE', 'subcmd'=>'GENERAL', 'datatype'=>'OPTIONS', 'modulename'=>'BTPENDANT', 
      'sensorid'=>'#{@badge}', 'moduleidx'=>'0', 'processtype'=>'1', 'count_or_ms'=>'0', 'trackingid'=>@@cmd_count, 'response_addr'=>response_addr, 
      'jsontxt'=>{'device'=>'#{@hub}', 'value'=>'#{@arg1}'})

    when 'getBadgeInfo'  #arg1 is string DEVICE_NAME, MODEL_NUMBER, SERIAL_NUMBER, FIRMWARE_REV, MANUFACTURER_NAME
      req.set_form_data('type' => 'cmd', 'cmd'=>'READ', 'subcmd'=>'#{@arg1}', 'datatype'=>'ID', 'modulename'=>'BTPENDANT', 
      'sensorid'=>'#{@badge}', 'moduleidx'=>'0', 'processtype'=>'1', 'count_or_ms'=>'0', 'trackingid'=>@@cmd_count, 'response_addr'=>response_addr,
      'jsontxt'=>{'device'=>'#{@hub}'})

    else
      Delayed::Worker.logger.error "SendHubCommandJob: Unexpected command"
    end

    res = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(req)
      #Delayed::Worker.logger.info response.inspect
    end

    case res
      when Net::HTTPSuccess, Net::HTTPRedirection
      # OK
    else
      # TODO figure how handle error
      res.value
    end
    Delayed::Worker.logger.debug "SendHubCommandJob: #{@res.to_s}"
  end  #perform
end



via Chebli Mohamed

Sprockets unable to locate stylesheets in a gem

Sprockets is unable to find stylesheets and javascript bundled in a gem. It raises the exception couldn't find file 'fullcalendar' with type 'text/css'

My application.css includes *= require fullcalendar and the result of running Rails.application.config.assets.paths includes "/usr/local/rvm/gems/ruby-2.2.1/gems/fullcalendar-rails-2.3.1.0/vendor/assets/stylesheets"

From what I understand, require should be looking in the vendor folder for stylesheets named fullcalendar, but it doesn't seem to be.

Are there any configurations I need to make before Sprockets will check this other folder?



via Chebli Mohamed

Datetime fails to save but without error

I try saving a row that has an attribute named class_datetime (which is a DateTime) and it silently fails. Here's an example:

I create a new LittleClassSession, like so:

irb(main):010:0> l = LittleClassSession.new
=> #<LittleClassSession id: nil, length: nil, class_datetime: nil, created_at: nil, updated_at: nil, little_class_id: nil, location_id: nil, session_series_token: nil>

The class_datetime is a DateTime:

irb(main):011:0> LittleClassSession.columns_hash["class_datetime"].type
=> :datetime

I set the attribute:

irb(main):012:0> l.class_datetime = DateTime.now
=> 2015-08-13 22:02:09 -0400

And I save (no validations yet):

irb(main):013:0> l.save
   (0.1ms)  begin transaction
  SQL (0.4ms)  INSERT INTO "little_class_sessions" ("class_datetime", "created_at", "updated_at") VALUES (?, ?, ?)  [["class_datetime", "2015-08-13 22:02:09.976030"], ["created_at", "2015-08-13 22:03:01.255911"], ["updated_at", "2015-08-13 22:03:01.255911"]]
   (2.6ms)  commit transaction
=> true

Looks like it worked. Let's see what I saved:

irb(main):014:0> l
=> #<LittleClassSession id: 728, length: nil, class_datetime: "2015-08-14 02:02:09", created_at: "2015-08-14 02:03:01", updated_at: "2015-08-14 02:03:01", little_class_id: nil, location_id: nil, session_series_token: nil>

Let's see what's in the table:

irb(main):015:0> LittleClassSession.last
  LittleClassSession Load (0.2ms)  SELECT  "little_class_sessions".* FROM "little_class_sessions"   ORDER BY "little_class_sessions"."id" DESC LIMIT 1
=> #<LittleClassSession id: 728, length: nil, class_datetime: nil, created_at: nil, updated_at: nil, little_class_id: nil, location_id: nil, session_series_token: nil>

What could be causing this? Recently I changed the default timezone in application.rb, but I don't see why that might be the reason.



via Chebli Mohamed

What's the proper way to run Ruby scripts in parallel?

Current I have the following code to run some ruby scripts, within a ruby script:

def run(base_directory, run_count)
  working_directory = base_directory.gsub("\n","")
  for i in 1..run_count
    system("ruby " + working_directory + i.to_s + "\\" + "main.rb " +   working_directory + i.to_s + "\\")
  end
end

However this runs the scripts in a sequence, but I need them to run in parallel. Where I have 10 scripts to run, and I want to run 5 at a time until I reach the number of scripts that needs run. Is there a simple way to accomplish this?



via Chebli Mohamed

Active Admin sort by 2nd level Association

I have three Models. Both makes and models table have name column inside.

class Review < ActiveRecord::Base
    belongs_to :model
end

class Model < ActiveRecord::Base
    belongs_to :make
    has_many :reviews
end

class Make < ActiveRecord::Base
    has_many :models
end 

In Active Admin on Index Page I want to sort reviews by make and model. I figured out how to sort it by model, because it has key the reviews table. Tried a lot of things. Nothing works to sort by make name. I was able to list though.

column "Model", sortable: 'model_id' do |p|
    p.model.name
end
column "Make", sortable: 'make_id' do |review|
    review.model.make.name
end

Only sorting by model name works. I think if I add make_id to Reviews it will be working, but it seems redundant, cause a chain like review.model.make perfectly works



via Chebli Mohamed

can't write unknown attribute `info' PrawnPDF

I'm using Prawn PDF to generate an invoice PDF on the fly and I keep getting the error "can't write unknown attribute 'info'" but I don't have an attribute 'info' anywhere in any of the concerned database tables (or my entire database for that matter). I don't know if it's something in the gem that I'm missing. Here is the tutorial I'm following: http://ift.tt/1hxJaWh and http://ift.tt/1fahQW9

I did register the mime type in the initializer (didn't show bc it's so simple, but I can if that's needed)

I also restarted the server multiple times to make sure that wasn't the issue.

I know the gem is installed properly because I can generate an empty PDF no problem, but when I try to add in @invoice is when I run into the issue.

Invoice Show Controller Action:

def show
    @invoice = Invoice.find(params[:id])
    @customer = @invoice.customer
    @user = current_user
    @company = @user.company

    respond_to do |format|
        format.html
        format.pdf do
            pdf = InvoicePdf.new(@invoice)
            send_data pdf.render, filename: "invoice_#{@invoice.created_at.strftime("%m/%d/%Y")}.pdf", type: "application/pdf"
        end
    end
end

InvoicePdf.rb

class InvoicePdf < Prawn::Document

    def intialize(invoice)
        super()
        @invoice = invoice
    end

    def header
        image "http://ift.tt/1cjbqFH", width: 530, height: 150
    end

    def text_content
        y_position = cursor - 50

        bounding_box([0, y_position], :width => 270, :height => 300) do
          text "Lorem ipsum", size: 15, style: :bold
          text "Lorem ipsum dolor sit amet, consectetur adipiscing elit.  Suspendisse interdum semper placerat. Aenean mattis fringilla risus ut fermentum. Fusce posuere dictum venenatis. Aliquam id tincidunt ante, eu pretium eros. Sed eget risus a nisl aliquet scelerisque sit amet id nisi. Praesent porta molestie ipsum, ac commodo erat hendrerit nec. Nullam interdum ipsum a quam euismod, at consequat libero bibendum. Nam at nulla fermentum, congue lectus ut, pulvinar nisl. Curabitur consectetur quis libero id laoreet. Fusce dictum metus et orci pretium, vel imperdiet est viverra. Morbi vitae libero in tortor mattis commodo. Ut sodales libero erat, at gravida enim rhoncus ut."
        end

        bounding_box([300, y_position], :width => 270, :height => 300) do
          text "Duis vel", size: 15, style: :bold
          text "Duis vel tortor elementum, ultrices tortor vel, accumsan dui. Nullam in dolor rutrum, gravida turpis eu, vestibulum lectus. Pellentesque aliquet dignissim justo ut fringilla. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut venenatis massa non eros venenatis aliquet. Suspendisse potenti. Mauris sed tincidunt mauris, et vulputate risus. Aliquam eget nibh at erat dignissim aliquam non et risus. Fusce mattis neque id diam pulvinar, fermentum luctus enim porttitor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos."
        end
    end

end

Full Trace:

    activerecord (4.1.0) lib/active_record/attribute_methods/write.rb:72:in `write_attribute'
    activerecord (4.1.0) lib/active_record/attribute_methods/dirty.rb:68:in `write_attribute'
    activerecord (4.1.0) lib/active_record/attribute_methods.rb:390:in `[]='
    pdf-core (0.6.0) lib/pdf/core/document_state.rb:42:in `normalize_metadata'
    pdf-core (0.6.0) lib/pdf/core/document_state.rb:5:in `initialize'
    prawn (2.0.2) lib/prawn/document.rb:200:in `new'
    prawn (2.0.2) lib/prawn/document.rb:200:in `initialize'
    app/controllers/invoices_controller.rb:23:in `new'
    app/controllers/invoices_controller.rb:23:in `block (2 levels) in show'
    actionpack (4.1.0) lib/action_controller/metal/mime_responds.rb:258:in `call'
    actionpack (4.1.0) lib/action_controller/metal/mime_responds.rb:258:in `respond_to'
    app/controllers/invoices_controller.rb:20:in `show'
    actionpack (4.1.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
    actionpack (4.1.0) lib/abstract_controller/base.rb:189:in `process_action'
    actionpack (4.1.0) lib/action_controller/metal/rendering.rb:10:in `process_action'
    actionpack (4.1.0) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
    activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:113:in `call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
    activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
    activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
    activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:149:in `block in halting_and_conditional'
    activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:229:in `block in halting'
    activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:166:in `block in halting'
    activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:86:in `run_callbacks'
    actionpack (4.1.0) lib/abstract_controller/callbacks.rb:19:in `process_action'
    actionpack (4.1.0) lib/action_controller/metal/rescue.rb:29:in `process_action'
    actionpack (4.1.0) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
    activesupport (4.1.0) lib/active_support/notifications.rb:159:in `block in instrument'
    activesupport (4.1.0) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
    activesupport (4.1.0) lib/active_support/notifications.rb:159:in `instrument'
    actionpack (4.1.0) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
    actionpack (4.1.0) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
    activerecord (4.1.0) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
    actionpack (4.1.0) lib/abstract_controller/base.rb:136:in `process'
    actionview (4.1.0) lib/action_view/rendering.rb:30:in `process'
    actionpack (4.1.0) lib/action_controller/metal.rb:195:in `dispatch'
    actionpack (4.1.0) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
    actionpack (4.1.0) lib/action_controller/metal.rb:231:in `block in action'
    actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:80:in `call'
    actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:80:in `dispatch'
    actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:48:in `call'
    actionpack (4.1.0) lib/action_dispatch/journey/router.rb:71:in `block in call'
    actionpack (4.1.0) lib/action_dispatch/journey/router.rb:59:in `each'
    actionpack (4.1.0) lib/action_dispatch/journey/router.rb:59:in `call'
    actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:676:in `call'
    omniauth (1.2.2) lib/omniauth/strategy.rb:186:in `call!'
    omniauth (1.2.2) lib/omniauth/strategy.rb:164:in `call'
    warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
    warden (1.2.3) lib/warden/manager.rb:34:in `catch'
    warden (1.2.3) lib/warden/manager.rb:34:in `call'
    rack (1.5.2) lib/rack/etag.rb:23:in `call'
    rack (1.5.2) lib/rack/conditionalget.rb:25:in `call'
    rack (1.5.2) lib/rack/head.rb:11:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/flash.rb:254:in `call'
    rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
    rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/cookies.rb:560:in `call'
    activerecord (4.1.0) lib/active_record/query_cache.rb:36:in `call'
    activerecord (4.1.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:in `call'
    activerecord (4.1.0) lib/active_record/migration.rb:380:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
    activesupport (4.1.0) lib/active_support/callbacks.rb:82:in `run_callbacks'
    actionpack (4.1.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/reloader.rb:73:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
    better_errors (2.1.1) lib/better_errors/middleware.rb:59:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
    railties (4.1.0) lib/rails/rack/logger.rb:38:in `call_app'
    railties (4.1.0) lib/rails/rack/logger.rb:20:in `block in call'
    activesupport (4.1.0) lib/active_support/tagged_logging.rb:68:in `block in tagged'
    activesupport (4.1.0) lib/active_support/tagged_logging.rb:26:in `tagged'
    activesupport (4.1.0) lib/active_support/tagged_logging.rb:68:in `tagged'
    railties (4.1.0) lib/rails/rack/logger.rb:20:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
    rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
    rack (1.5.2) lib/rack/runtime.rb:17:in `call'
    activesupport (4.1.0) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
    rack (1.5.2) lib/rack/lock.rb:17:in `call'
    actionpack (4.1.0) lib/action_dispatch/middleware/static.rb:64:in `call'
    rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
    railties (4.1.0) lib/rails/engine.rb:514:in `call'
    railties (4.1.0) lib/rails/application.rb:144:in `call'
    rack (1.5.2) lib/rack/lock.rb:17:in `call'
    rack (1.5.2) lib/rack/content_length.rb:14:in `call'
    rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
    /home/action/.parts/packages/ruby2.1/2.1.1/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service'
    /home/action/.parts/packages/ruby2.1/2.1.1/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run'
    /home/action/.parts/packages/ruby2.1/2.1.1/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'



via Chebli Mohamed

Create an array of ids with rails

I am trying to create an array of ids so that I can query if a certain id is associated with an object. Here is my method but it isnt adding id's to the array.

class Report
  include Mongoid::Document

  has_and_belongs_to_many :reportapprovals, class_name: "Reportapproval", inverse_of: :report

  def bind_reportapproval
    @reportapprovals = Reportapproval.where(tenant_id: self.tenant_id).all

    if @reportapprovals.present? && @reportapprovals.any? { |ra| ra.tenant_approved == true }
      @reportapprovals.each do |ra|
        self.reportapproval_ids = ra.id
      end
    end
  end
end

This is suppose to add an array of reportapproval_ids to the report object.



via Chebli Mohamed

Can this raw SQL be written using the Rails Active Record Query Interface? Should it be?

In my Rails 4 app I make a fairly simple search for one of my models using the following SQL 'OR' statements. It works fine. Is there any way (and reason) to achieve this without raw SQL using the Rails Active Record Query Interface?

Activity.where("
    user_id = ? OR 
    category = ? OR 
    (secondary_id = ? AND secondary_model = ?) OR 
    (tertiary_id = ? AND tertiary_model = ?)",
    user_id, "Announcement", user_id, "user", user_id, "user"
).uniq



via Chebli Mohamed

Ruby on Rails multiple classes with same name under different namespace

So I have some classes in Rails that do a bit of funky stuff. I have some classes under a Rails application named ApplicationName. They are autoloaded as part of Rails on the boot of my application server. Some are ActiveRecord models and some are just PORO models that are created to deal with some other stuff and some are service classes which are also PORO's. Some of these classes have the same name but are under different namespaces such as User and NameSpaced::User which represent different objects with similar concepts. In one of the namespaced classes I do some ETL work to get a foreign object to meld into an ActiveRecord model in my database. Since the ActiveRecord model by default is under the global ApplicationName namespace I figured ApplicationName::ModelName would work and I would be returned the top level object (the ActiveRecord model) I expected. Instead I got an unintialized constant error. If I do a ApplicationName::Application::ModelName I am able to return it but I get a warning about the class referencing the toplevel namespace (as I expected considering the ActiveRecord object resides up there). The ModelName model conflicts with another model under a different namespace (for the sake of argument we'll call it DifferentNameSpace). All in all things look like:

module ApplicationName
  class Application < Rails::Application
   # do autoload stuff here
  end
end

class ModelName
end

module DifferentNameSpace
  class ModelName
  end
end

Is there any way to specifically call ApplicationName::ModelName or to do an ApplicationName::Application::ModelName without the warning? Right now it works if I do ::ModelName but that looks so...ugly.



via Chebli Mohamed

Rails collection_check_boxes - wrap each checkbox with

Brand new to Rails. How do I add a <li> wrapper to each checkbox / label element generated by the following code?

<%= f.collection_check_boxes :publish_to, [['YouTube'], ['Hulu'], ['Roku'], ['Owned Website'], ['Other']], :first, :first %>

The final outputted HTML would look like:

<li class="checkbox-wrap">
  <label></label>
  <input type="checkbox"/>
</li>

Thanks in advance!



via Chebli Mohamed

Paperclip files get deleted after each deploy

I use the Paperclip gem to store pictures, and on localhost it works perfectly. However, any pictures I add to my live app get deleted after every deploy.

I use Git to deploy. Here's my deployment process:

$ bundle exec cap production deploy
$ ssh root@xx.xxx.xx.xxx
$ chmod -R 777 /rails_apps/app/releases
$ cd /rails_apps/app/current
$ cp config/database.yml.sample config/database.yml
$ RAILS_ENV=production bundle exec rake assets:precompile
$ /etc/init.d/apache2 restart

Has anyone else run into something like this?


UPDATE:

This is not a duplicate, because the answer to this question, which is to add this line to my deploy.rb:

set :linked_dirs, fetch(:linked_dirs, []).push('public/system')

causes Paperclip to break entirely. Previously I had had an issue with not having permission to add images with Paperclip, resulting in this error:

Errno::EACCES in UsersController#update
Permission denied - /rails_apps/website/releases/20150807211111/public/system/users/avatars/000/000/562

But running this command on my server fixes the permissions:

chmod -R 777 /rails_apps/website/releases

However, modifying my deploy.rb file as shown above, causes the chmod -R 777 command to no longer work, and I once again don't have permission to add images, resulting in the same "Permission denied" error.

So that question does not supply a valid solution to my problem.



via Chebli Mohamed

Ruby on Rails - redirect_to the next video that is not marked as completed

How can I redirect to the next lesson that does not have userLesson (problem is lessons belongs to a course through a chapter)

Models:

class Course
    has_many :lessons, through: :chapters
end

class Lesson
 belongs_to :chapter
 has_one :lecture, through: :chapter
end

class User
  has_many :user_lessons
end

class UserLesson
  #fields: user_id, lesson_id, completed(boolean)  
  belongs_to :user
  belongs_to :lesson
end

class Chapter 
  has_many :lessons
  belongs_to :lecture
end 

here user_lessons_controller:

class UserLessonsController < ApplicationController
  before_filter :set_user_and_lesson
  def create
    @user_lesson = UserLession.create(user_id: @user.id, lession_id: @lesson.id, completed: true)
    if @user_lesson.save
      # redirect_to appropriate location
    else
      # take the appropriate action
    end
  end
 end

I want to redirect_to the next lesson that has not the UserLesson when saved. I have no idea how to do it as it belongs_to a chapter. Please help! Could you please help me with the query to write...



via Chebli Mohamed

rails 4 best inverse_of best practices?

I am developing a web app using rails 4 for the first time. I am making all of my model associations bidirectional and using inverse_of wherever it is allowed.

From reading the documentation, I've developed the impression that this is probably the best practice, but that's never really spelled out clearly anywhere.

I'd appreciate any general advice in this regard from experienced rails developers. I hope the question is not too vague to have value here.

Thanks!

Update: In addition to non-standard names, there appear to be two main additional cases where explicitly setting inverse_of is needed:

  1. for invalid_automatic_inverse_options ( http://ift.tt/1hAovkA )
  2. if you're accepting nested attributes as per ( http://ift.tt/1qoax2y )


via Chebli Mohamed

Ember.js input focus lost on valueBinding

I'm creating application with ember.js + Rails

Here is my templates/application.emblem:

#wrapper
  article.new
    = view Ember.TextField valueBinding='newPostName'

the problem is, that after clicking on input, and pressing any key, focus on that input is lost.

It happens only first time and I wonder why. After clicking again, I can type any string and everything works fine.

Here is my Gemfile:

gem 'ember-rails'
gem 'ember-source', '~> 1.13.5'
gem 'ember-emblem-template'
gem 'emblem-source'



via Chebli Mohamed

How to break Rails application and return 404 as JSON

Rails application working as API service. I use mongoid

In a controller i write now:

class UsersController < ApplicationController
  def show
    @user = User.find params[:user_id]
    unless @user
      render json: { error: I18n.t('user.messages.not_found') }, status: :not_found
      return
    end
    # ... some actions with @user object 
  end
end

I need make code cleaner and move this code in module. I assume that the code in controller may look like this:

class UsersController < ApplicationController
  def show
    @user = User.find params[:user_id]
    not_found? @user

    # ... some actions with @user object
  end
end

or like this

class UsersController < ApplicationController
  def show
    @user = found? User, params[:user_id]

    # ... some actions with @user object
  end
end

One of example how it can work is Pundit gem (http://ift.tt/1cmAaug). In my controller i write:

...
def index
  authorize User, :index?
  @users = User.all
end
...

if user hasn't access to this page then Pundit raise exception and return to client error message with 401 http code.

What is better way to refactor my code to make controllers cleaner?



via Chebli Mohamed