samedi 30 avril 2016

Rails need help in devise signup using only email

I am using rails 4 and devise 3. I want to allow user to sign-up using email only. After sign-up a mail should be sent with a link to set the password. Please let me know how to do this.

Bootstrap dropdown button not working when published to Heroku (Ruby on Rails)

I have already searched around StackOverflow and have been trying for a while to solve this, but none of them works.

Although I reordered the line in application.js and set precompile in production.rb to "true", it still does not work when pushed to Heroku. Locally, however, it is wokring fine.

Please take a look at my project file --> http://ift.tt/1pUH0Uj

I'm using ruby 2.2.4 and rails 4.2.6 on Ubuntu 14.04. Thanks

Error : 'incompatible library version' sqlite3-1.3.11 in rails

I working on Ubuntu system(16.04).

My problem is whenever i setup any rails project and try to run rails s then i got 'incompatible library version' error for sqlite3 something like below.

/home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/activesupport-4.0.0/lib/active_support/values/time_zone.rb:282: warning: circular argument reference - now
/home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/sqlite3-1.3.11/lib/sqlite3.rb:6:in `require': incompatible library version - /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.so (LoadError)
    from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/sqlite3-1.3.11/lib/sqlite3.rb:6:in `rescue in <top (required)>'
    from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/sqlite3-1.3.11/lib/sqlite3.rb:2:in `<top (required)>'
    from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:77:in `require'
    from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:77:in `block (2 levels) in require'
    from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:72:in `each'
    from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:72:in `block in require'
    from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:61:in `each'
    from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:61:in `require'
    from /usr/lib/ruby/vendor_ruby/bundler.rb:99:in `require'
    from /home/jiggs/sites/albumriverfinal/config/application.rb:7:in `<top (required)>'
    from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/railties-4.0.0/lib/rails/commands.rb:76:in `require'
    from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/railties-4.0.0/lib/rails/commands.rb:76:in `block in <top (required)>'
    from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/railties-4.0.0/lib/rails/commands.rb:73:in `tap'
    from /home/jiggs/.rvm/gems/ruby-2.3.1@albumriver/gems/railties-4.0.0/lib/rails/commands.rb:73:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

Rails version : 4.0.0

ruby version i tried with rails 4.0.0 :

  • ruby-2.0.0-p247 [ x86_64 ]

  • ruby-2.2.5 [ x86_64 ]

  • ruby-2.3.0 [ x86_64 ]

  • ruby-2.3.0-preview1 [ x86_64 ]

  • ruby-2.3.1 [ x86_64 ]

Hidden attribute not populating field in form for Rails 3.2

I'm implementing an invitation system and I want the new user form to pre-populate the user's email address in the email address field on the form (eventually, I will refactor this so it's not a form_field), so that the user doesn't have to type in all their information, just enter a password.

I have created the getter/setter methods in the users.rb model like this:

  def invitation_token
    invitation.invitation_token if invitation
  end
  def invitation_token=(invitation_token)
    self.invitation = Invitation.find_by_invitation_token(invitation_token)
  end

INVITATION MODEL

class Invitation < ActiveRecord::Base

  #--== ASSOCIATIONS
  belongs_to :sender, :class_name => 'User'
  has_one :recipient, :class_name => 'User'
  #--== CALLBACKS
  before_create :generate_token
  before_create :recipient_is_not_registered
  before_create :decrement_sender_count, :if => :sender
  #--== VALIDATIONS
  validates_presence_of :recipient_email
  #validate :recipient_is_not_registered
  validate :sender_has_invitations, :if => :sender
  #--== METHODS
  private
    def recipient_is_not_registered
      if User.find_by_email(recipient_email)
        false
      else
        true
      end
    end

    def sender_has_invitations
      unless sender.invitation_limit > 0
        redirect_to root_url
      end
    end

    def generate_token  #TODO: MOVE to lib/generate_token.rb
      self.invitation_token = Digest::SHA1.hexdigest([Time.now, rand].join)
    end

    def decrement_sender_count
      sender.decrement! :invitation_limit
    end

end

USER CONTROLLER

class UsersController < ApplicationController
  def new
    @user = User.new(:invitation_token => params[:invitation_token])
    @user.email = @user.invitation.recipient_email if @user.invitation
  end

  def create
    @user = User.new(user_params)
    if @user.save
      session[:user_id] = @user.id
      redirect_to root_url, notice: "Thank you for signing up!"
    else
      render "new"
    end
  end

 ...

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

views/users/_form.html.erb

<%= form_for @user do |f| %>  

  <%= f.hidden_field :invitation_token %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </div>
  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
  </div>
  <div class="field">
    <%= f.check_box :admin %>
    <%= f.label :admin %>
  </div>
  <div class="actions"><%= f.submit %></div>
<% end %>

I was following Ryan Bates' RC#124 - Beta Invitations, and got stuck here. His code doesn't produce the error, so I should mention that this is a Rails 3.2.18 app.

When I reload the form, the user's email isn't populated in the form. The relevant log shows:

Started GET "/signup.914823d28d07b747213ec3de47f89ad537169e34" for 127.0.0.1 
at 2016-04-30 20:24:47 -0600
Processing by UsersController#new as 
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."auth_token" = 'rOHiKmDcceytxi_t151YIQ' LIMIT 1
  Invitation Load (0.0ms)  SELECT "invitations".* FROM "invitations" WHERE "invitations"."invitation_token" IS NULL LIMIT 1
  Rendered users/_form.html.erb (5.0ms)
  Rendered users/new.html.erb within layouts/application (6.0ms)
Completed 200 OK in 102.0ms (Views: 25.0ms | ActiveRecord: 3.0ms)

So it appears that the invitation_token isn't being passed in, since the log shows it is NULL.

I have gone over the RC code from top to bottom and can't find out why it's not being passed.

Any help would be appreciated. Thanks.

UPDATE: The output from the view source is:

<input id="user_invitation_token" name="user[invitation_token]" type="hidden" />, so it's not being passed along.

How to Send Password Forget mail to User upon activation of Account in Rails

In our Application Users are created by Admin with a Random Password . So we send Activation Mail to User (http://localhost:3000/users/confirmation?confirmation_token=1xxxxxxxxxxxxxx")
We Use devise_for :users

def confirmation_required?
    true
end

So now We want when User activate his Account then automatically they send a Password Forget mail to him on his mail ID

What configuration for Rails 3.2.22.2 + Puma + Heroku?

I've read Richard Schneeman's article, and a bunch of other ones. ;-) I'm still struggling with this.

Here's few gems I've added in my Gemfile to benchmark my app:

gem 'airbrake'
gem 'newrelic_rpm'
gem 'stackprof'
gem 'derailed', group: :development
gem 'rack-mini-profiler'
gem 'flamegraph'
gem 'memory_profiler'
gem "skylight"

After a lots of benchmarks in development and in staging env, I know where my app is not fast enough but there's not memory leak (some small mem bloats sometimes maybe).

newapp-staging app is the new version (aka: new frontend, upgraded gems, optimized queries, ...) of oldapp-production app. Please have a look at the screenshots (oldapp-production use webrick, newapp-staging use puma)

So here comes 2 simple questions:

question #1

newapp-staging app is using ruby '2.2.0' & rails '3.2.22.2' and I can't ensure that it is threadsafe because of my code and the associated gems, so... I must use 1 thread at a time. Is puma an advantage here? Metrics are telling me not. OR... my configuration is not good. (missing preload_app! maybe, or other things?) Here's my Procfile:

web: bundle exec puma -t 1:1 -p ${PORT:-3000} -e ${RACK_ENV:-development}
worker: bundle exec rake jobs:work

question #2

Unicorn could be used as a replacement?

Thank you for your time and your advices.

Cheers

OLD APP NEW APP

vendredi 29 avril 2016

Questions on method return values and arguments after do

sorry for this noob question I am just not able to understand ruby/rails grammer,

In rails 2.x, I read the following code,

def localized_input_form_for(record_or_name_or_array, *args, &proc)
    options = args.extract_options!
    args << options.merge(:builder=>LocalizedFormBuilder)
    concat('<div class="inputbox">')
    form_for(record_or_name_or_array, *args, &proc)
    concat('</div>')
end

What does the above function return? Shouldn't it be the return value of the last line statement concat('</div>')?

In the views, I have,

<% localized_input_form_for(@customer) do |f| %>

What is the f in the above code, is it the same f as form_for(xx) do |f|?

The following code works without problem,

<%= f.text_field :name, :required => true, :size => 30,:class =>'ime_on' %>

In rails 4, I made the following modification,

def localized_input_form_for(record_or_name_or_array, *args, &proc)
    options = args.extract_options!
    args << options.merge(:builder=>LocalizedFormBuilder)
    concat('<div class="inputbox">'.html_safe)
    concat(form_for(record_or_name_or_array, *args, &proc))
    concat('</div>'.html_safe)
end

Without adding concat out of form_for, and without adding html_safe, the original code just doesnt work.

Now, everything still works, the

<% localized_input_form_for(@customer) do |f| %>

works without problem, the form is shown exactly as before. So what is the return value of this function now? and what is f above?

The only difference is, the original options in

<%= f.text_field :name, :required => true, :size => 30,:class =>'ime_on' %>

which are, required: true, size: 30, and class:'ime_on' don't show in the final html!

It generates the following,

<input type="text" value="abc" name="customer[name]" id="customer_name">

without size, class etc options. The html generated by rails 2.x do have these options showing up.

I am just confused about the difference. And I also don't understand why the original rails 2.x and rails 4 both worked (the |f| reflects the form generated by form_for, so f.text_field will get the right value from database).

Carrierwave How to uplaoad without extenstion

I want to upload a image (iTunesArtwork) without extension from console, I want to skip validating the image when I upload from console.

I am able to upload it from the UI without any extension added with image.

Model

class App < ActiveRecord::Base
  mount_uploader :itunes_artwork, ItunesArtworkUploader
end

Uploader

class ItunesArtworkUploader < IconBase
DIMENSIONS = [1024, 1024]
def filename
  "iTunesArtwork"
end

def extension_white_list
  ['png', '']
end

end

Console:

> app.remote_itunes_artwork_url = "http://ift.tt/248wGe7
> app.save!
ActiveRecord::RecordInvalid: Validation failed: Itunes artwork must be in png format

How to change calender structure and save multple dates

When i add multiple dates with 'input' field i'm getting. First i got error like this "undefined method `map' for "translation missing: de.date.order":String"

so that in my locales i added like this

`de:
 date: #Throws an exception otherwise.
    order:
      - "year"
      - "month"
      - "day"'

so that error disappered ,and data is saving to database and calender came like this structure.

enter image description here

Because of this i changed 'input' to 'text_field' , so that calender is coming perfect like this enter image description here

but data is not saving to database. then where i made the error.

PLease Help.i need to change the calender struture and data also need to be stored in database

my model

class Property < ActiveRecord::Base has_many :property_dates accepts_nested_attributes_for :property_dates, allow_destroy: true end

    class PropertyDate < ActiveRecord::Base
        belongs_to :property
    end`

                                           
                                           
<%= f.input :property_dates, required: true,label:false,:class=>"upload imgUpload" %>
 <%= f.simple_fields_for :property_dates do |i| %>
               <%= i.input :start_date%>
               <%= i.input :end_date%>
<% end %>
<%= f.link_to_add 'Add Date', :property_dates, class: 'btn btn-primary', data: {target: '.additional-dates-images'} %>

jeudi 28 avril 2016

Embarrassed to ask about Ruby, specifically Ruby on Rails, but here is

So I am leaving a job that is solely Java stack, and moving to one that doesn't outwardly admit it, but they are absolutely Ruby/Rails crazy.

I think I can understand Ruby as I am recently out of university and in this new age of Software Engineering it is imperative to pick up languages quickly, but "Rails" doesn't seem to be much more than an MVC framework which the Ruby language is placed upon.

I'm sure there are plenty of people rolling over right now wondering how I could be so naive, but seriously... please help me understand what Ruby is w/o Rails and vice versa...

Willing to take any readings or books suggested! Sorry, I'm new to the game! Thanks!

NoMethodError: undefined method 'clients' for nil:NilClass

I've run into the infamous NoMethodError which I can't seem to crack, even after browsing the number of SO posts.

Note: I am running on Cloud9 development environment

I'm making a productivity website where a user can have their clients, projects, etc.

I'm attempting to run the clients_display_test.rb test and am receiving the following terminal error.

Any help would be appreciated but I would ask, if you determine where my mistake is, please specify where my lack of technical understanding was :)

  1) Error:
ClientsDisplayTestTest#test_profile_display:
NoMethodError: undefined method `clients' for nil:NilClass
    app/controllers/clients_controller.rb:4:in `index'
    test/integration/clients_display_test_test.rb:11:in `block in <class:ClientsDisplayTestTest>'

48 runs, 127 assertions, 0 failures, 1 errors, 0 skips

clients_display_test.rb

require 'test_helper'

class ClientsDisplayTestTest < ActionDispatch::IntegrationTest
  include ApplicationHelper

  def setup
    @user = users(:Robert)
  end 

  test "profile display" do
    get '/clients'
    assert_template "clients/index"
    assert_select 'title', "Clients"
  end
end

Attached is some .rb files which hopefully could help:

clients_controller.rb

class ClientsController < ApplicationController

    def index
        @clients = current_user.clients.paginate(page: params[:page])
    end

    def show
    end
end

routes.rb

Rails.application.routes.draw do

  get 'password_resets/newedit'

  root              'static_pages#home'
  get 'about' =>    'static_pages#about'
  get 'signup' =>   'users#new'

  get 'login' =>    'sessions#new'
  #the page for new session
  post 'login' =>   'sessions#create'
  #creates a new session
  delete 'logout' =>'sessions#destroy'
  #deletes the session
  get '/clients' => 'clients#index'
  get '/clients/show' => 'clients#show'

  resources :users
  resources :clients 
  resources :account_activations, only: [:edit]
  resources :password_resets,     only: [:new, :create, :edit, :update]
end

Client Views:

index.html.erb

    <%= provide(:title, 'Clients') %>

<div class="clients-container container"> 
    <div class="row">
        <!-- Add pagination later for multiple folders over multiple pages --> 
    <% if current_user.clients.any? %>
        <%= render @clients %> 
        <%= will_paginate @clients %>
    <% end %>
    </div>
</div>

_client.html.erb

<div class="col-md-2 client-folder" style="margin: 10px" id="client - <%= client.id %>">
  <span class="clientName" ><%= client.client_name %></span> <br>
  <span class="contactName"><%= client.contact_name %></span>
</div>

Rails - Many to many methods

So in my rails app there are lots of events and I want a user to be able to create a calendar of their own composed of the events. My current code is below, but I cannot use User.events or User.user_calendar at all and from my understanding of rails associations this shouldn't be a problem.

event.rb

has_and_belongs_to_many :days
has_many :user_calendars
has_many :users, through: :user_calendars

user.rb

has_many :user_calendars
has_many :events, through: :user_calendars

user_calendar.rb

belongs_to :users
belongs_to :event

migration.rb

create_table :user_calendars do |t|
  t.integer :user_id
  t.integer :event_id
  t.timestamps null: false
end

I simply want to be able to create a list of events unique to each user, but obviously any updates on a given event must be reflected on that event if it is within an user calendar.

Rails association - Customised list of items from existing list

I am developing a rails app where users can add tasks they wish to do to a customised list of their own. Each task can also belong to 0 or more categories. So far I've tried this:

user.rb

has_one :user_list
has_many :tasks, through: :user_list

user_list.rb

belongs_to :user
has_many   :tasks

tasks.rb

has_and_belongs_to_many :categories

[timestamp}_migration.rb

create_table :user_lists do |t|
  t.integer :user_id
  t.integer :task_id

  t.timestamps null: false
end

The issue I am having is in the console I try to run User.find(1).tasks it cannot find the column tasks.user_list_id when using the following query:

SELECT "tasks".* FROM "tasks" INNER JOIN "user_lists" ON "tasks"."user_list_id" = "user_lists"."id" WHERE "user_lists"."user_id" = ?  [["user_id", 1]]

This query should be joining the tasks id from the tasks table with the tasks id on the user_lists table. Are the associations correct and if so what can I do to change the query?

Summing an array of numbers in ruby and extracting time over 40 hours

I wrote a payroll type app which takes a clock_event and has a punch_in and punch_out field. In a the clock_event class I have a method that takes the employee, sums their total hours and exports to CSV. This gives total hours for the employee, and then a total sum of their total_hours which is a method in the class calculated on the fly.

Here is my code:

clock_event.rb

 def total_hours
    self.clock_out.to_i - self.clock_in.to_i
  end

  def self.to_csv(records = [], options = {})
          CSV.generate(options) do |csv|
            csv << ["Employee", "Clock-In", "Clock-Out", "Station", "Comment", "Total Shift Hours"]
              records.each do |ce|
              csv << [ce.user.try(:full_name), ce.formatted_clock_in, ce.formatted_clock_out, ce.station.try(:station_name), ce.comment, TimeFormatter.format_time(ce.total_hours)]
            end
           records.map(&:user).uniq.each do |user|
             csv << ["Total Hours for: #{user.full_name}"]
             csv << [TimeFormatter.format_time(records.select{ |r| r.user == user}.sum(&:total_hours))]
           end

            csv << ["Total Payroll Hours"]
            csv << [TimeFormatter.format_time(records.sum(&:total_hours))]
          end
        end
    end

This method works and exports a CSV with all total time entries for each day then a sum of the hours at the bottom of the CSV file.

Here's my problem...

I can sum no problem, but I need to show the following:

1.) Total Sum of hours (done) 2.) Any hours over 40 hours I need to pull that amount into another field in the CSV file. So if an employee hits 40 hours it will show the 40 hours in one field then show the remaining ours as overtime right next to it.

I know how to sum the hours but am unsure as to how to extra the hours over 40 into another field into the CSV.

I'm sure there's a Ruby way to do it but I'm not certain on how this would work.

Any help would be greatly appreciated. If you need more code or context, please let me know.

How to detect if dates are consecutive in Rails?

I'm looking to check for consecutive dates and display them differently if they are consecutive.

I'm working with Garage Sales that have multiple dates per sale. I'd like to then cycle through each date, and group any consecutive dates to display as a group: Ex: Apr 28 - Apr 30

I also need to account for non-consecutive dates: Ex: Apr 15, Apr 28 - 30

Additionally, weekly dates need to be recognized as non-consecutive (so basically avoid step checks): Ex: Apr 16, Apr 23, Apr 30


So far, I'm taking each date that hasn't passed & ordering them properly.

garage_sale_dates.where("date > ?",Time.now).order(:date)

Thanks for any help! Let me know if any other info is needed.

Why would you be using config.assets.prefix in rails?

I'm trying to figure out, whether I should be using config.assets.prefixin my development environment or not.

When I'm using localhost, for development, are there any (dis-)advantages of doing this? When the local server itself isn't caching and is on another domain (production-domain vs localhost), I fail to see the disadvantages? Especially for hard-coding some paths in CSS and Javascript, which will then always return 404's on development..

I've been using config.assets.prefix = "/dev-assets" as pr. reccomendation of another developer, who isn't working with us anymore.

Is this a problem, that anyone else have thought about and taken a standpoint at?

create Form For basic Class not Model

Lets say I have a class that generates a PDF as output. Different attributes can passed to it when initializing it.

 PDFGenerate.new(page: 4, user: 5, year: 2016, day: 13 ....)

Now I would like to create an View/Controller for that Class so that the user can simply create a PDF over the Web Applicaction. I would like to do something like that:

class PDFController < ActionController::Base
    def index
       @pdf_generate = PDFGenerate.new
    end

    def show
       send_data PDFGenerate.new(params).inline
    end
end

In my view I would like to have:

<%= form_for @pdf_generate do |f| %>

<%=  f.text_field :page %>
.......

But it is not working like this because @pdf_generate Is not a Model. How can I create a Form for a Basic Class like PDFGenerate ? Thanks

how can i override simple_form bootstrap style with my bootstrap form styles

i have built simple_form fields in my railsapp,when i adding simple_form tag it style get changes, and i want to integrate this simple_form with my alredy built frontend bootstrap forms this is my

bootstrap form

<input type="text" class="form-control" placeholder="Username" required autofocus />

simple_form filed

<%= f.input :email,html:{class: "form-control"},required: false,autofocus: true %>

mercredi 27 avril 2016

Rails 3.2 to 4.0 Upgrade: Undefined method to_datetime for false:FalseClass

I'm upgrading a Rails application I've inherited from 3.2 to 4.0.1. I followed and finished the edge guide here:

http://ift.tt/YwRK6e

I've gotten everything fixed except for a single error that I can't seem to find the root cause of. When I attempt to save a User model object, I'm met with the following error:

[1] pry(main)> User.create(name: "test user", email: "testuser@frobnitz.com", password: "testPassword123", password_confirmation: "testPassword123")                                                                                                                               

(0.6ms)  BEGIN
(0.9ms)  ROLLBACK
NoMethodError: undefined method `to_datetime' for false:FalseClass
from /home/cmhobbs/src/serve2perform/.gem/ruby/2.3.0/gems/activesupport-4.0.1/lib/active_support/core_ext/date_time/calculations.rb:161:in `<=>'

activesupport 4.0.1 and rals 4.0.1 are installed. I use chgems and I purged my .gem/ directory and Gemfile.lock before bundling again.

Here is a Gist of the User model.

And here is all of the backtrace output I could get from pry.

Here is a link to the User table schema.

How to update self referential association attributes in rails way?

I have one model which has has_many :through self referential association to it.

I'm creating and updating the child records in the single form, so far i'm successfully being able to create and update the child records using the manual approach. (Manually passing the Id of the parent record to the child)

I need to know/understand what should be the standard approach to create and update record for self referential association?

There are many reasons to follow the rails way here as it will help in handling errors at the creation part in a better way and also with updating child records and deleting one of the child records.

Model Template

class Template < ActiveRecord::Base

  has_many :related_templates, :foreign_key => :parent_id
  has_many :children, :through => :related_templates, :source => :child

  has_many :inverse_related_templates, class_name: "RelatedTemplate", :foreign_key => :child_id
  has_many :parents, :through => :inverse_related_templates, :source => :parent

end

Please note that my rails application is behaving as an api so i dont have rails forms in the views.

I need to know how will i white list the child attributes in the form and how will i write the create, update and delete method.

For white listing child attributes i tried using

accepts_nested_attributes_for :children and children_attributes in the controller but it is still unpermitted_parameter.

If needed i'll update my approach here (the manual way)

Caching sql queries in a Rails controller

I have this code:

class RecipeToolsController < Api::BaseController
      skip_before_filter :set_cache_buster

      def index
        expires_in 30.minutes, public: true

        recipe = Recipe.find(params[:recipe_id])
        recipe_tools = (recipe.recipe_tools + RecipeTool.generic)

        render json: recipe_tools, each_serializer: Api::V20150315::RecipeToolSerializer
        ...
  end

The RecipeTool.generic code queries the same 3 RecipeTool objects every time. Is there a way to cache that query so it doesn't have to fire every single time?

.generic is simply this scope:

scope :generic, -> { where(generic: true) }

What can I do to cache this and expire it every so often?

This is an API endpoint.

It just seems silly that this always queries a very similar subject of RecipeTools unless the tools change. So who should be expiring this cache? Can the user of the API request a cache refresh?

change active color of nav-pills

This is the code i'm using to make the pills in my navbar active..

  <ul class="nav nav-pills">

  <li class="<%= 'active' if current_page?(root_path) %>"><% yield (:home)%><%= link_to "Home", root_path%></li>

however it uses the default blue color as "active" how should i change this?

this is what i have in my css already

.nav>li>a:hover,

.nav>li>a:focus{

 background-color: #5c8a36;}

even with this (the color should be green) it still shows up as the default blue color

How to run this expression in ruby on rails

I have two models

class Filters < ActiveRecord::Base
end

class Groups < ActiveRecord::Base
end

Filter model is responsible for fetching user data from db e.g

filter_id_1. SELECT users.* FROM users INNER JOIN notes ON notes.user_id = users.id WHERE notes.category = 'Emotions'

filter_id_2. SELECT users.* FROM users INNER JOIN subscriptions ON subscriptions.user_id = users.id WHERE (Date(end_date) = CURDATE())

filter_id_3. SELECT users.* FROM users WHERE (auth_token_created_at > DATE_SUB(NOW(), INTERVAL 2 hour))

Group model makes a group with multiple filters with AND and OR conditions e.g

group_id_1 = "filter_id_1 AND filter_id_2 OR filter_id_3"

Now using group I am trying to fetch users by converting expression to methods according to AND OR conditions.

users = Filter.find(1).get_users &  Filter.find(2).get_users | Filter.find(3).get_users

How can i convert this experssion from this "filter_id_1 AND filter_id_2 OR filter_id_3"

to this

users = Filter.find(1).get_users & Filter.find(2).get_users | Filter.find(3).get_users

How to save multiple dates in ruby

i have 2 models property and property dates. i need to save multiple start date and end date for a property in property dates tables table fields(property_id,start_date_end_date) my model tables

`class Property < ActiveRecord::Base
    has_many :property_dates
    accepts_nested_attributes_for :property_dates
end`
`class PropertyDate < ActiveRecord::Base
        belongs_to :property
end`
my controller
class Users::PropertiesController < ApplicationController
  before_filter :authenticate_user!
  before_action :set_properties, only: [:show, :edit, :update, :destroy]


  def index
    @properties =  Property.where(:user_id=>current_user.id)
  end

  def list
    @properties = Property.all
  end

  def show

  end

 
  def new
   @property= Property.new
  end

  
  def edit
  end

  def create
    @property = Property.new(properties_params)
    respond_to do |format|
      if @property.save
 format.json { render :index, status: :created, location: @property }
      else
        format.html { render :new }
        format.json { render json: @property.errors, status: :unprocessable_entity }
      end
    end
  end

 
  def update
    respond_to do |format|
      if @property.update(properties_params)
        format.json { render :back, status: :ok, location: @property }
      else
        format.json { render json: @property.errors, status: :unprocessable_entity }
      end
    end
  end

 
  def destroy
    @property.destroy
    respond_to do |format|
      format.html { redirect_to  :back, notice: 'Property was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_properties
      @property = Property.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def properties_params
      params.require(:property).permit(:Space_name,:user_id,:address,:pincode,:image,property_dates_attributes: [ :start_date, :end_date ])

form property form i need to select multiple dates and need to save to property_dates table

my form.html.erb

 `<%= simple_nested_form_for ([:users,@property])  do |f| %>
  <%= f.fields_for :property_dates do |p| %>
    <%= p.text_field :start_date%>
    <%= p.text_field :end_date%>
  <% end %>
  <% end %>`

When i write form it is not visible in my form. Why it is happening like that? Any error in my code. Please help.

Autoload a gem only when needed in rails 3.2?

I'm trying to figure out how to load a specific gem only when needed. Here the scenario:

I'm using the great axlsx gem to create Excel files. The feature in my app allowing this is called only when the user ask for a Excel file:

# model
require 'axlsx'
class AssessmentRaw < ActiveRecord::Base
    # fun stuff here
    def create_excel_file_io
        xls = Axlsx::Package.new
        # fun stuff here too
    end
end

# a call in a controller
@assessment_raw_instance.create_excel_file_io

Using derailed gem I can see that axlsx is heavy on memory:

axlsx: 9.8516 MiB (Also required by: /path-to-rails/app/models/assessment_raw)
  axlsx/workbook/workbook.rb: 3.5391 MiB
    axlsx/workbook/worksheet/worksheet.rb: 0.3477 MiB
  axlsx/drawing/drawing.rb: 1.8438 MiB
  zip: 1.6797 MiB
    zip/entry: 0.3047 MiB
  axlsx/stylesheet/styles.rb: 0.8516 MiB
  htmlentities: 0.5273 MiB
    htmlentities/flavors: 0.4453 MiB
      htmlentities/mappings/expanded: 0.4258 MiB
  axlsx/util/simple_typed_list.rb: 0.4727 MiB

So I wonder... if rails/ruby allow lazy loading for a gem?

Hope I'm clear enough. :-) Thank you!

Using puma on Heroku with Rails 3.2.22.2 and Ruby 2.2, not threadsafe? What is the point?

I've deployed a rails app 3.2.22.2 running on ruby 2.2.0p0 on heroku with puma as web server.

Heroku loves puma and advice new apps to use it:

http://ift.tt/1lDF8Ls

Puma uses threads, in addition to worker processes, to make more use of available CPU. You can only utilize threads in Puma if your entire code-base is thread safe. Otherwise, you can still use Puma, but must only scale out through worker processes.

I can't ensure my rails app (my code in fact) and the gems are threadsafe, so my only option is to add some workers and configure my Procfile like this:

web: bundle exec puma -t 1:1 -p ${PORT:-3000} -e ${RACK_ENV:-development}
worker: bundle exec rake jobs:work

Just in case, I've also set the config vars as:

=== myapp-staging Config Vars
DATABASE_URL:          http://postgresthis:that@addresse:port/more
LANG:                  en_US.UTF-8
MIN_THREADS:           1
NEW_RELIC_LICENSE_KEY: key
NEW_RELIC_LOG:         stdout
PAPERTRAIL_API_TOKEN:  key
RACK_ENV:              staging
RAILS_ENV:             staging
RAILS_MAX_THREADS:     1
SENSIBLE_DEFAULTS:     enabled
WEBSOLR_URL:           http://ift.tt/235Mbhj
WEB_CONCURRENCY:       1

So... if I can only use only 1 thread, is puma the right solution for my app?

Thank you!

Paperclip transparency issue

I'm using paperclip for image uploads on my rails 3 app. When I upload an image with a transparent background it converts the transparency to black. Any idea how to fix this issue?

How does where not in rails 3 works

Here is a code snippet

Wip.where(status: "P").where("reason NOT IN ?", ['DOB_MISSING'])

This does not work.

I have tried looking for it and found a lot of questions asked. Some of them have suggested this but I am not sure where I am going wrong

mardi 26 avril 2016

Cron Jobs and Background Tasks

I am studying about Cron Jobs and Background Tasks in Roby On Rails. Can anyone tell me which one to use as currently I am using Whenever Gem. Why whenever is better than Sidekiq.

How to render json for more than one outer join tables with 'includes' option

i have a outer join active record. i need to display json for the outer join query. This is the active record i have written

@recent_details=Property.includes(:space_amenities,:event_suitabilities,:purpose_suitabilities,:venue_categories).where(id: params[:id]) respond_to do |format| format.json { render :json => @recent_details.to_json(include: :venue_categories)} end

here in json part, with include option i included only one outer join table. i need to include all these 4(:space_amenities,:event_suitabilities,:purpose_suitabilities,:venue_categories) tables in include option. how to include all these while rendering json.

Any help is appreiatable.

Rails migration -- not appearing on show.html.erb

I had a scaffold named b_page I wanted to create another column , so I ran a migration:

rails g migration add_status_to_b_page status:string

so migration was successful. Users should be able to update their status so I put this on the _form.html.erb:

<div class="field">
<%= f.label :status %><br>
<%= f.text_field :status %>
</div>

was successful but then i added it to the show.html.erb

<%= @b_page.status %>

but everytime i make a new b_page or edit the current one I dont see it on show.html.erb

I get a "Pending Error" whenever I click on Pay using Payola-Payment Gem (A gem made for Stripe) in my Rails 4.2.1 application

Using Payola-Payments Gem to handle Stripe Payments, it's necessary to set Background Worker for your transaction. After setting up Background Worker using ActiveJob, I will get error when I click pay.

Here is it:

Note: Am using Windows Environment (Windows 8) and I believe there is something am doing wrong here. Error Alert Renders on my View:

This seems to be taking too long. Please contact support and give them transaction ID: ook4dp

Here is the generated code from Console

Started POST "/payola/buy/job/excelwithcode-7d492bf330ab66b0eaa61ce2ce277e14" for 127.0.0.1 at 2016-04-25 20:50:26 +0100
Processing by Payola::TransactionsController#create as */*
  Parameters: {"stripeToken"=>"tok_184FksCc1zXXaitaOrD5ELaH", "stripeEmail"=>"neededforpayments@mybusinesstest.com", "authenticity_token"=>"Uod7Ue4XHNcCvayA6G1shiiI43QKoBOrbImnwt0TGFHVlp11WdHaNTcPl/0UyYefcT6foowc30bFdtK0cJuXog==", "product_class"=>"job", "permalink"=>"excelwithcode-7d492bf330ab66b0eaa61ce2ce277e14"}
  Payola::Affiliate Load (1.0ms)  SELECT  "payola_affiliates".* FROM "payola_affiliates" WHERE (lower(code) = lower(NULL))  ORDER BY "payola_affiliates"."id" ASC LIMIT 1
  Job Load (1.0ms)  SELECT  "jobs".* FROM "jobs" WHERE "jobs"."permalink" = ? LIMIT 1  [["permalink", "excelwithcode-7d492bf330ab66b0eaa61ce2ce277e14"]]
  Payola::Coupon Load (1.0ms)  SELECT  "payola_coupons".* FROM "payola_coupons" WHERE (lower(code) = lower(NULL))  ORDER BY "payola_coupons"."id" ASC LIMIT 1
   (1.0ms)  begin transaction
  Payola::Sale Exists (0.0ms)  SELECT  1 AS one FROM "payola_sales" WHERE "payola_sales"."guid" IS NULL LIMIT 1
  CACHE (0.0ms)  SELECT  1 AS one FROM "payola_sales" WHERE "payola_sales"."guid" IS NULL LIMIT 1
  Payola::Sale Exists (1.0ms)  SELECT  1 AS one FROM "payola_sales" WHERE "payola_sales"."guid" = 'ook4dp' LIMIT 1
  SQL (1.0ms)  INSERT INTO "payola_sales" ("product_id", "product_type", "email", "stripe_token", "currency", "amount", "state", "guid", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["product_id", 1], ["product_type", "Job"], ["email", "neededforpayments@mybusinesstest.com"], ["stripe_token", "tok_184FksCc1zXXaitaOrD5ELaH"], ["currency", "usd"], ["amount", 20000], ["state", "pending"], ["guid", "ook4dp"], ["created_at", "2016-04-25 19:50:26.639939"], ["updated_at", "2016-04-25 19:50:26.639939"]]
  SQL (0.0ms)  INSERT INTO "versions" ("event", "created_at", "item_id", "item_type") VALUES (?, ?, ?, ?)  [["event", "create"], ["created_at", "2016-04-25 19:50:26.639939"], ["item_id", 2], ["item_type", "Payola::Sale"]]
   (150.3ms)  commit transaction
[ActiveJob] Enqueued Payola::Worker::ActiveJob (Job ID: 72e9235d-e2f2-42d6-8ae4-0a74dd8bce5d) to DelayedJob(default) with arguments: "Payola::ProcessSale", "ook4dp"
[ActiveJob]    (0.0ms)  begin transaction
[ActiveJob]   SQL (1.0ms)  INSERT INTO "delayed_jobs" ("queue", "handler", "run_at", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?)  [["queue", "default"], ["handler", "--- !ruby/object:ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper\njob_data:\n  job_class: Payola::Worker::ActiveJob\n  job_id: 72e9235d-e2f2-42d6-8ae4-0a74dd8bce5d\n  queue_name: default\n  arguments:\n  - Payola::ProcessSale\n  - ook4dp\n"], ["run_at", "2016-04-25 19:50:26.812282"], ["created_at", "2016-04-25 19:50:26.812282"], ["updated_at", "2016-04-25 19:50:26.812282"]]
[ActiveJob]    (87.0ms)  commit transaction
Completed 200 OK in 284ms (Views: 1.0ms | ActiveRecord: 244.3ms)


Started GET "/payola/status/ook4dp" for 127.0.0.1 at 2016-04-25 20:50:26 +0100
Processing by Payola::TransactionsController#status as */*
  Parameters: {"guid"=>"ook4dp"}
  Payola::Affiliate Load (1.0ms)  SELECT  "payola_affiliates".* FROM "payola_affiliates" WHERE (lower(code) = lower(NULL))  ORDER BY "payola_affiliates"."id" ASC LIMIT 1
  Payola::Sale Load (1.0ms)  SELECT  "payola_sales".* FROM "payola_sales" WHERE "payola_sales"."guid" = ? LIMIT 1  [["guid", "ook4dp"]]
Completed 200 OK in 8ms (Views: 1.0ms | ActiveRecord: 2.0ms)


Started GET "/payola/status/ook4dp" for 127.0.0.1 at 2016-04-25 20:50:28 +0100
Processing by Payola::TransactionsController#status as */*
  Parameters: {"guid"=>"ook4dp"}
  Payola::Affiliate Load (1.0ms)  SELECT  "payola_affiliates".* FROM "payola_affiliates" WHERE (lower(code) = lower(NULL))  ORDER BY "payola_affiliates"."id" ASC LIMIT 1
  Payola::Sale Load (1.0ms)  SELECT  "payola_sales".* FROM "payola_sales" WHERE "payola_sales"."guid" = ? LIMIT 1  [["guid", "ook4dp"]]
Completed 200 OK in 8ms (Views: 0.0ms | ActiveRecord: 2.0ms)

Under Network Tab from my Browser I get the following

{guid: "ook4dp", status: "pending", error: null}
error: null
guid: "ook4dp"
status: "pending"

config/application.rb

require File.expand_path('../boot', __FILE__)

require 'rails/all'
require 'active_job'
require 'active_record'
require 'action_controller'
require 'action_view'

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module App
  class Application < Rails::Application
    config.i18n.enforce_available_locales = true

    config.action_controller.action_on_unpermitted_parameters = :raise
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de

    config.active_record.raise_in_transactional_callbacks = true

    config.active_job.queue_adapter = :delayed_job

  end
end

model/job.rb

class Job < ActiveRecord::Base
  include Payola::Sellable

  validates :title,
            :category,
            :location,
            :description,
            :company_name,
            :website,
            :email,
            :to_apply,
            presence: true
  validates :title, length: { maximum: 75 }
  validates :description, length: { minimum: 300 }
  validates :to_apply, length: { maximum: 500 }

  validates_formatting_of :email, using: :email
  validates_formatting_of :website, using: :url

  before_validation :provide_name, :provide_permalink

  def self.paid_ad
    where.not('stripeEmail' => nil).where.not('payola_sale_guid' => nil).where('created_at > ?', 30.days.ago)
  end

  def paid?
    (!(self.stripeEmail == nil) && !(self.payola_sale_guid == nil))
  end

  def self.search(params)
    jobs = Job.where('name like ? or description like?', "%#{params[:search]}%', '%#{params[:search]}%" ) if params [:search]
    jobs
  end


  private

  def provide_name
    self.name = 'excelwithcode' if self.name == nil
  end

  def provide_permalink
    self.permalink = "#{ self.name } #{ SecureRandom.hex }".parameterize if self.permalink == nil
  end
end

Looking at my development log, I understand the transaction keeps repeating itself because of Background Worker using ActiveJob which I set, but the main problem is that the transaction never gets successful and my Error alert responds on my Stripe Custom Payment Form as described above. In other words, once you click PAY, it freezes.

I still don't know why this happened and I need your help. Thanks for helping in advance

Rails 3.2 Refactoring With Rubycritic

I have this code in my r_grids_controller.rb

before_filter -> {find_rgrid_by_user params[:user_id]}, only: [:update_admin_call, :update_admin_email,
                                                             :update_admin_offline, :update_onboarded]

.........
def update_admin_email
  old_admin_email = @rgrid.admin_email
  @rgrid.update_attribute('admin_email', !old_admin_email)
  respond_to do |format|
    format.js { render 'update_checkbox', :locals => {:checkbox_name => "email_#{params[:user_id]}"}}
  end
end

def update_admin_call
  old_admin_call = @rgrid.admin_call
  @rgrid.update_attribute('admin_call', !old_admin_call)
  respond_to do |format|
    format.js { render 'update_checkbox', :locals => {:checkbox_name => "call_#{params[:user_id]}"}}
  end
end

def update_admin_offline
  old_admin_offline = @rgrid.admin_offline
  @rgrid.update_attribute('admin_offline', !old_admin_offline)
  respond_to do |format|
    format.js { render 'update_checkbox', :locals => {:checkbox_name => "offline_#{params[:user_id]}"}}
  end
end

def update_onboarded
  old_onboarded = @rgrid.onboarded
  @rgrid.update_attribute('onboarded', !old_onboarded)
  respond_to do |format|
    format.js { render 'update_checkbox', :locals => {:checkbox_name => "onboarded_#{params[:user_id]}"}}
  end
end

private

def find_rgrid_by_user(user_id)
  @rgrid = RGrid.find_by_user_id(user_id)
end

using RubyCritic, it says me that these 4 blocks are 'DuplicateCode'. However, I don't know how can I refactor this to keep it DRY.

Somebody has an idea? :-)

test-unit automatic runner produce "invalid option" error on rake tasks?

Since I've installed gon, my rake tasks aren't working anymore.

I'm using:

Rails 3.2.22.2
ruby 2.2.0p0
gon-6.0.1
test-unit-3.0.8

I can't uninstall test-unit because:

$ rails c
/Users/me/.rbenv/versions/2.2.0/gemsets/project-gems/gems/activesupport-3.2.22.2/lib/active_support/dependencies.rb:251:in `require': Please add test-unit gem to your Gemfile: `gem 'test-unit', '~> 3.0'` (cannot load such file -- test/unit/testcase) (LoadError)

If I rake -T for example:

rake about                                       # List versions of all Rails frameworks and the environment
... (all rake tasks here) ...
rake tmp:create                                  # Creates tmp directories for sessions, cache, sockets, and pids
invalid option: -T
Test::Unit automatic runner.
Usage: /Users/me/.rbenv/versions/2.2.0/gemsets/project-gems/bin/rake [options] [-- untouched arguments]
    -r, --runner=RUNNER              Use the given RUNNER.
                                     (c[onsole], e[macs], x[ml])
        --collector=COLLECTOR        Use the given COLLECTOR.
                                     (de[scendant], di[r], l[oad], o[bject]_space)
    -n, --name=NAME                  Runs tests matching NAME.
                                     Use '/PATTERN/' for NAME to use regular expression.
        --ignore-name=NAME           Ignores tests matching NAME.
                                     Use '/PATTERN/' for NAME to use regular expression.
    -t, --testcase=TESTCASE          Runs tests in TestCases matching TESTCASE.
                                     Use '/PATTERN/' for TESTCASE to use regular expression.
        --ignore-testcase=TESTCASE   Ignores tests in TestCases matching TESTCASE.
                                     Use '/PATTERN/' for TESTCASE to use regular expression.
        --location=LOCATION          Runs tests that defined in LOCATION.
                                     LOCATION is one of PATH:LINE, PATH or LINE
        --attribute=EXPRESSION       Runs tests that matches EXPRESSION.
                                     EXPRESSION is evaluated as Ruby's expression.
                                     Test attribute name can be used with no receiver in EXPRESSION.
                                     EXPRESSION examples:
                                       !slow
                                       tag == 'important' and !slow
        --[no-]priority-mode         Runs some tests based on their priority.
        --default-priority=PRIORITY  Uses PRIORITY as default priority
                                     (h[igh], i[mportant], l[ow], m[ust], ne[ver], no[rmal])
    -I, --load-path=DIR[:DIR...]     Appends directory list to $LOAD_PATH.
        --color-scheme=SCHEME        Use SCHEME as color scheme.
                                     (d[efault])
        --config=FILE                Use YAML fomat FILE content as configuration file.
        --order=ORDER                Run tests in a test case in ORDER order.
                                     (a[lphabetic], d[efined], r[andom])
        --max-diff-target-string-size=SIZE
                                     Shows diff if both expected result string size and actual result string size are less than or equal SIZE in bytes.
                                     (1000)
    -v, --verbose=[LEVEL]            Set the output level (default is verbose).
                                     (important-only, n[ormal], p[rogress], s[ilent], v[erbose])
        --[no-]use-color=[auto]      Uses color output
                                     (default is auto)
        --progress-row-max=MAX       Uses MAX as max terminal width for progress mark
                                     (default is auto)
        --no-show-detail-immediately Shows not passed test details immediately.
                                     (default is yes)
        --output-file-descriptor=FD  Outputs to file descriptor FD
        --                           Stop processing options so that the
                                     remaining options will be passed to the
                                     test.
    -h, --help                       Display this help.

Deprecated options:
        --console                    Console runner (use --runner).

Here's the culprit:

invalid option: -T
Test::Unit automatic runner.

With or without rspec, same error.

Current solution: I ended with those lines at the bottom of my application.rb:

Test::Unit::AutoRunner.need_auto_run = false if defined?(Test::Unit::AutoRunner)

first link

Test::Unit.run = true if defined?(Test::Unit) && Test::Unit.respond_to?(:run=)

second link

Anyone with a better idea?

Thank you!

ps: http://ift.tt/24hd4Bc

overridey Destroy but keep callbacks

ActiveRecod model which overrides the destroy method to actually just "soft-delete" the object. We do create many before_filters, dynamically but they won't be called, if we override the destroy method.

before_destroy {
  p "before_destroy"
}

def destroy
  soft_delete
end

How to do outer join in rails

I need to outer join in rails

@recent_details = Property.joins(:space_amenities,:event_suitabilities,:purpose_suitabilities,:venue_categories).where(id: params[:id])

this active record gives me inner join. but i need outer join with this active record.

please help Any help is appreciable

lundi 25 avril 2016

assets:precompile: uglify.js failed to open due to invalid conversion sequence from utf-8 to shift_jis

This is a weird problem.

My config.encoding is set to shift_jis (so all database/excel etc will be read in as shift_jis by default).

When I execue (windows environment)

> rake assets:precompile RAILS_ENV="production"

There's such error:

rake aborted!
Encoding::UndefinedConversionError: U+00A0 from UTF-8 to Shift_JIS
C:/Ruby22/lib/ruby/gems/2.2.0/gems/uglifier-3.0.0/lib/uglifier.rb:156:in `read'
C:/Ruby22/lib/ruby/gems/2.2.0/gems/uglifier-3.0.0/lib/uglifier.rb:156:in `open'

The line 156 of uglifier.rb is:

  File.open(file, "r:UTF-8", &:read)

Initially I thought it's because of my own css or js file that causes problem, I then tried to convert all my js/css files to utf-8/shift_jis and there's no use.

I then try to print out the file name, I found that the one that causes this error is uglifier.js.

However, uglifier.js has no Japanese characters, why opening uglfier.js will cause

Encoding::UndefinedConversionError: U+00A0 from UTF-8 to Shift_JIS

?

Can anyone help?

Thank you very much.

Silencing "Cache read" statements in Rails development.log for all my assets

I'm trying to figure out how to quiet the very distracting Cache read: http://localhost:3000/assets/... statements in my Rails development.log, which really slow me down with all the scrolling they cause me to do.

In my development log, after the SQL statements, and reads/writes for cache fragments (which is still useful and I want to keep), there is a long list of Cache read statements for all the js, css, and images being used on the requested page. Just to show a handful:

Cache read: http://localhost:3000/assets/jquery.atwho.css?body=1
Cache read: http://localhost:3000/assets/jquery.selectric.css?body=1
Cache read: http://localhost:3000/assets/font-awesome.css?body=1
Cache read: http://localhost:3000/assets/480.css?body=1
Cache read: http://localhost:3000/assets/768.css?body=1

I'm using the quiet_assets gem as was suggested in another SO post, but that's not working on these "Cache read" statements.

Is there some simple setting I'm missing in config/environments/development.rb to not output these to the log? Thanks everyone

Is stubbing appropriate for this activerecord query?

This code exists in a model:

  def self.ensure_exists(user_id:, coupon_id:, app_context: nil)
    candidate = where(user_id: user_id, coupon_id: coupon_id).first_or_initialize
    candidate.updated_at = Time.now.utc
    if candidate.new_record?
      log_invite_event!(app_context)
    end
...

private

  def log_invite_event!(app_context)
    invite = coupon.try(:invite)
    if invite.present?
      Event.create!(
        event_type: Event::EventType::INVITEE_ACCOUNT_STARTED,
        date: Time.now.utc,
        eventable: invite,
        description: "Invitee entered email address",
        app_context: app_context
      )
    end
  end

I want to test that log_invite_event! gets called on the candidate object. IN short, the method looks for an existing candidate, and takes the first one or initializes it. That first_or_initialize method is here

How do I test this? I have this as a start:

candidate = CouponCandidate.new
allow(CouponCandidate).to receive(:where).with(hash_including(user_id: user.id, coupon_id: coupon.id).and return(candidate)
allow(candidate).to receive(:first_or_initialize).and return(candidate)

expect(candidate).to receive(:log_invite_event).with(app_context)

subject

How do I test that private method? As written, I feel like I need to make that method non-private and have candidate be the explicit receiver. Right?

How to assign file content to chef node attribute

I have fingreprint.txt at the location "#{node['abc.d']}/fingreprint.txt"

The contents of the file are as below:
time="2015-03-25T17:53:12C" level=info msg="SHA1 Fingerprint=7F:D0:19:C5:80:42:66"

Now I want to retrieve the value of fingerprint and assign it to chef attribute
I am using the following ruby block

ruby_block "retrieve_fingerprint" do  
    block do  
        path="#{node['abc.d']}/fingreprint.txt"  
        Chef::Resource::RubyBlock.send(:include, Chef::Mixin::ShellOut)  
        command = 'grep -Po '(?<=Fingerprint=)[^"]*' path '  
        command_out = shell_out(command)  
        node.default['fingerprint'] = command_out.stdout  
    end  
    action :create  
end  

It seems not to be working because of missing escape chars. Please let me know if there is some other way of assigning file content to node attribute

Ruby on rials Change Column to Null, Not Work?

I command in Terminal to change on column in database to not null, but It seems not work.

rails g migration change_column_null :Speaker, :surname, false

I got a file ChangeColumnNull But inside, it is nothing.

class ChangeColumnNull < ActiveRecord::Migration
def change
end
end

I do not know why it is no working... Thanks Guys

Rails updating DB constantly (external values)

I would like to ask if there is any way how to update database from external source to my Rails DB constantly (every 1 hour)...

I was trying to do that but when i do that my DB is duplicated + added new files so is there any if statement where can i just add new values?

  • I'm pulling DB (JSON) from BitBucket(commits)
  • Then i'm saving that into my Rails DB and returning in view.
  • I tried for that use whenever gem.

bitbucket.rb

class Bitbucket < ActiveRecord::Base
  def self.savedata
    require 'bitbucket_rest_api'   
    bitbucket = BitBucket.new login:'...', password:'...'
    repo = bitbucket.repos.commits.list '...', '...'
    repo["values"].each do |r|
      create(
        name: r["author"]["user"]["display_name"],
        message: r["message"],
        date: r["date"]
      )
    end
  end
end

I have to run first in Rails console Bitbucket.connection then Bitbucket.savedata to save into DB.

Thanks for any advice and help.

how can i display other listings posted by the same user? [on hold]

my controller for showing action

def show
  if @listing.reviews.blank?
     @average_review = 0
  else
     @average_review = @listing.reviews.average(:rating).round(2)
  end
  @listings = Listing.find(params[:id])
  impressionist(@listings)
end

How to write checkbox active record search using using scope

How to do checkbox search through scope in ruby

i have form like this <%VenueCategory.all.each do |c|%> <%= check_box_tag("venue_categories[]", c.id)%> <%= c.name%> <%end%>

i want to search venue categories if more than one option is selected. How to do it with scope

i tried like this in my property.rb model

scope :venue_category, -> (venue_categories) { where venue_category_id: venue_categories }

in my controller @properties = @properties.venue_categories(params[:venue_categories]) if params[:venue_categories].present?

i'm getting error when i tried this. I dont know how to do mulptiple checkbox options search with scope. Please help me if anyone knows. Any help is appreciatable.

How to access previous updated_at?

I have model in which I keep track of the field updated_at.

Is there a way I can track the previous updated_at?

For example

updated_at = A (where A is an actual datetime stamp)

Some work is done then save is called

updated_at = B (where B is an actual datetime stamp)

Is there a way I can access the previous updated_at i.e. A?

How to write active record using using scope

How to write active record for price less than or equal to and price less than or equal to by scope in ruby.

i tried like this.

scope :price, -> (price_lteq_or_price_gteq) { where("price_paisas >= ? or price_paisas <= ?", price_lteq_or_price_gteq, price_lteq_or_price_gteq)}

Controller

def index
  @properties = Property.where(:status=>'1')
  @properties = @properties.status(params[:status]) if params[:status].present?
  @properties = @properties.price(params[:price_lteq]) if params[:price_lteq].present?
  @properties = @properties.price(params[:price_gteq]) if params[:price_gteq].present?
end

when i tried like this,i got query like this

SELECT `properties`.* FROM `properties` WHERE `properties`.`status` = '1' AND (price_paisas >= '000' or price_paisas <= '000') AND (price_paisas >= '49900' or price_paisas <= '49900')

`

what i need is active record like this

SELECT `properties`.* FROM `properties` WHERE `properties`.`status` = '1' AND (price_paisas >= '000' and price_paisas <='49900')

How to do so. Please help. Any help is appreciable.

Create two navigation link for single table in rails_admin gem

I have one table named User.

In that i have two type of record :

1) Corporation

2) Agency

Field name is is_agency?(Boolean). If is agency then true and if is corporation then false.

I want to display User table to two different table Corporation and Agency in admin side. I used rails_admin gem.

How can i differentiate using "is_agency?" field ?

I check rails_admin gem documentation but i did't find any thing about this.

Please help me to find out this solution, it will save my hours.

how can i add ditricts collection through simple_form

I have added countries list in my railsapp,and i dont know How to add collection of district and state in railapp through simple_form?

dimanche 24 avril 2016

delayed_job undefined method `to_datetime' for false:FalseClass

I am using delayed job with the following versions of dependent packages

/var/lib/gems/2.3.0/gems/delayed_job-4.0.6
/var/lib/gems/2.3.0/gems/delayed_job_active_record-4.0.1
/var/lib/gems/2.3.0/gems/activerecord-3.2.13
/var/lib/gems/2.3.0/gems/activesupport-3.2.13

When I do Article.delay.create I get

undefined method `to_datetime' for false:FalseClass

Same versions on production server works fine Here is the entire trace

http://ift.tt/1NrMsZT

Rails Beginner NoMethodError in PinsController#new

having issues keep getting error undefined method `pins' for nil:NilClass, can someone explain how to fix this error. Been following a tutorial and recently got stuck.


pins_controller.rb

class PinsController < ApplicationController
    before_action :find_pin, only: [:show, :edit, :update, :destroy]


    def index
        @pins = Pin.all.order("created_at DESC")
    end

    def new
        @pin = current_user.pins.build
    end


    def create
        @pin = current_user.pins.build(pin_params)

        if @pin.save
            redirect_to @pin, notice: "Successfully created new Pin"
        else
            render 'new'
        end
    end

    def edit

    end

    def update
        if @pin.update(pin_params)
            redirect_to @pin, notice: "Pin was Successfully updated!"
        else
            render 'edit'
        end
    end


    def destroy
        @pin.destroy
        redirect_to root_path
    end


    private

    def pin_params
        params.require(:pin).permit(:title, :description)
    end

    def find_pin
        @pin = Pin.find(params[:id])
    end
end


user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
    has_many :pins     
end


pin.rb

class Pin < ActiveRecord::Base
    belongs_to :user
end


routes.rb

Rails.application.routes.draw do
  devise_for :users
resources :pins

root "pins#index"
end

Ruby on rails File Upload and download

Here I want to fulfil the function which is to upload file and then download in ruby on rails.

First I add function in Application Controller

def uploadFile(file)
if !file.original_filename.empty
  @filename = getFileName(file.original_filename)
  File.open("#{RAILS_ROOT}/public/files/#{@filename}", "wb") do |f|
    f.write(file.read)
  end
  return @filename
end
end

def getFileName(filename)
if !filename.nil
  return filename
end
end

def save(file, description)
@filename=getFileName(file.original_filename)
@filesize=getFileName(file.length)
@uploadfile = Uploadfile.new
@uploadfile.filename=@filename
@uploadfile.filesize=@filesize/1024
@uploadfile.description=description
@uploadfile.save
end

Second, I add upload in my controller which is for file upload.

def upload
@uploadfile = Uploadfile.new
unless request.get
  i=params[:file].size
  for num in(0..i-1)
  if filename=uploadFile(params[:file][num])
    savefiles(params[:file][num],params[:uploadfile][num])
  end
end
end
end

Finally, I add html in my new.html.erb which is the page I am gonna to upload file and submit.

  <%=form_tag ({:action=>"upload"}), :multipart=>true %>
  <divid="MyFile">
  <inputid="file"name="file[]"size="30"type="file"/></br>
  <inputtype="text"id="uploadfile_description"name="uploadfile[]"></br>
</div>
<inputtype="button"value="add"onclick="addText()"/>
<inputstyle="cursor:pointer"type="submit"value="upload"/>
<%=form_tag%>

Eventually, I still got mistakes on this.

No route matches {:action=>"upload", :controller=>"cplectures"}

How am I going to fix it without paperclip or other gems, and after that how to download this file from the front side with a download button. Thanks guys

How to iterate after some data?

I have a product model with has_many images model

so on the first loop i just get the first 4 images

 <%  @product.images.first(4).each do |i| %>
    <li>
      <a href="<%= i.photo.url.to_s %>">
        <%= image_tag(i.photo.url(:small).to_s, :class => 'thumbnail circle', :'data-zoom-href' => i.photo.url(:big).to_s) %>
      </a>
    </li>
       <% end %>

how to loop the rest of images after the first 4 images?

i've tried this: without sucess!

 <ul>


  <%  @product.images.last.each do |i| %>
    <li>
      <a href="<%= i.photo.url.to_s %>">
        <%= image_tag(i.photo.url(:small).to_s, :class => 'thumbnail circle', :'data-zoom-href' => i.photo.url(:big).to_s) %>
      </a>
    </li>
       <% end %>


  </ul>

Specifying layout in namespaced controller

I am creating a new version of one of my controllers,

Original Controller:-

class ExampleController < ApplicationController
layout 'filename', only: [:method_name]
 ...
 def method_name
   #...some logic...
   respond_to do |format|
   format.html
   format.json {
     render json: {}, root: false
   }
   end
 end
...
end

New Controller:-

class V1::ExampleController < ApplicationController
layout 'filename', only: [:method_name]
...
 def method_name
   #...some logic...
   respond_to do |format|
   format.html
   format.json {
     render json: {}, root: false
   }
   end
 end
...
end

I keep getting error:-

Missing template v1/example/filename, application/filename with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :arb, :haml, :jbuilder]}

One of the solution is to create a folder structure v1/example and put my layout file there too. But I do not want to create duplicate copies of this file.

Another is to use a parent controller class of both new and old example_controller and specify layout there(and have a folder structure according to the name of the parent class). But this will be an overkill and also I plan on deleting old controller once all my clients migrate to new versions.

I also tried specifying like this:-

class V1::ExampleController < ApplicationController
layout 'example/filename', only: [:method_name]
...
end

but this also doesn't work.

How to tell my new controller to render layout from the old folder structure.

Issues with assets compilation (Sprockets + custom preprocessor)

I'm on a Ruby on Rails project using ReactJS, so almost 100% Javascript (well, coffeescript + jsx).

I've made a very simple preprocessor for sprockets to replace $imagePath("xxx") to the real asset path.

It looks like this:

module JSAssetPathPreprocessor
  @in_processing = {}
  class << self
    def call(input)
      # For some reason we can have an infinite loop here...
      unless @in_processing[input[:filename]]
        @in_processing[input[:filename]] = true
        out = input[:data].gsub(/\$imagePath\(['"](.*?)['"]\)/){ "'#{ActionController::Base.helpers.image_path($1)}'" }
        @in_processing.delete(input[:filename])
        return { data: out }
      else
        return { data: input[:data] }
      end
    end
  end
end

Then I register it in initializers

Sprockets.register_preprocessor('application/javascript', JSAssetPathPreprocessor) 

And tada! It's working !

(coffeescript + reactJS)

# ...
<Image src=$imagePath('banners/blocks/01.jpg') />
# ...

Output:

<img src="/assets/banners/blocks/01-69a091fe87763b439602a274a03fb63e5357deed56802a55d1547cd67091bd18.jpg">

Except once I deploy in production, the path is not the good one:

<img src="/images/banners/blocks/01.jpg">

I'm using capistrano and do rake tmp:cache:clear assets:clobber assets:precompile.

I've no clues about what's wrong, doing all of this in local works well, I checked my generated application.js. But not on my server.

I even tested with RAILS_ENV=production in local... And it works T_T.

The assets are regenerated well in production (eg. if I add console.log("xxx") it will display on next release, so no caching problem) but the path still remain wrong.

Any clues or ideas on where I can check ? I guess my preprocessor sucks but I get hard time finding documentation for this version of sprockets.

Useful gems version.

  • rails (= 5.0.0.beta3)
  • sprockets (3.6.0)
  • browserify + react-rails + sprockets-coffee-react

ruby on rails Database Column Change

How am I'm going to change one column in Database. For example, I Create a Table Lecture, However, I forgot to set some columns as NOT NULL and some other requests.

What commands should I use in Terminal in order to do some changes in this column?

Thanks guys

How to plan a model relation for collage admission app in rails

How to plan a model relation for collage admission app in rails
i want student basic Registraion&login
after login it redirects to student RegistraionForm conation student contact details and student marks forms

Student contactdetails form contains

student contact form
    first name
    last name
    address
    mobile no
    gender
    fathers name
    fathers occupation
    mothers name.  

Student marks list conatins

**registraion form**
    .
    |-- Board of examination
    |   `-- Branches(ex:science,:humanities)
    |       `--science[when i choose science]
               `--science subject1
               `--science subject2
               `--common paper for sciecnce and humanities
    |       `--humanities[when is choose humanities]
               `--humanities subject1
               `--humanities subject2
               `--common paper for sciecnce and humanities

samedi 23 avril 2016

Configuring a Project for a Database Ruby on Rails

So I'm new to programing and I'm teaching myself Ruby on Rails to get started. I have mysql running and I've downloaded Ruby ruby 2.3.0 and Rails 3.2.22.2 because these are the versions being used in the video tutorial.

I was generating a controller & view, however when it came to the moment of truth to see if everything worked there were problems. I programmed index.html.erb to say "hello world" in my browser but received this message:

ActiveRecord::ConnectionNotEstablished

I believe this is because it's trying to contact the database. So I started to create the database on mysml, and as I reach the point where I create a schema.rb in the dp folder. Only when I type the command in terminal I get this:

julian$ rake db:schema:dump
rake aborted!
LoadError: Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter` (can't activate mysql2 (~> 0.3.10), already activated mysql2-0.4.4. Make sure all dependencies are added to Gemfile.)
/Users/julian/Sites/simple_cms/config/environment.rb:5:in `<top (required)>'
Gem::LoadError: can't activate mysql2 (~> 0.3.10), already activated mysql2-0.4.4. Make sure all dependencies are added to Gemfile.
/Users/julian/Sites/simple_cms/config/environment.rb:5:in `<top (required)>'
Tasks: TOP => db:schema:dump => environment
(See full trace by running task with --trace)

What do I do? I have been stuck on this for hours, does anyone have some guidance?

vendredi 22 avril 2016

Rails - Products From Database Not Showing Up On Windows

In my group project, we're developing a Rails e-commerce website. I'm using a Mac, while the rest of my teammates are using Windows. I gave us a start at the database by adding a Products column, and was able to create some dummy data. It shows up on my side in our products page, but when my teammates get the project from GitHub, the products don't show up.

They tried running rake db:migrate and rake db:seed with no success at solving the problem. Any idea why the database objects are not showing up for them?

On my Mac, I'm using Ruby version 2.3.0 and they're using 2.2.4 since Windows gives them issues if they have a higher version. Is this what might be causing the issue?

We're all new to Ruby on Rails, so any help would be appreciated. Thanks.

Rails 3.2 to 4.0 Upgrade: Undefined method to_datetime for false:FalseClass

I'm upgrading a Rails application I've inherited from 3.2 to 4.0.1. I followed and finished the edge guide here:

http://ift.tt/YwRK6e

I've gotten everything fixed except for a single error that I can't seem to find the root cause of. When I attempt to save a User model object, I'm met with the following error:

[1] pry(main)> User.create(name: "test user", email: "testuser@frobnitz.com", password: "testPassword123", password_confirmation: "testPassword123")                                                                                                                               

(0.6ms)  BEGIN
(0.9ms)  ROLLBACK
NoMethodError: undefined method `to_datetime' for false:FalseClass
from /home/cmhobbs/src/serve2perform/.gem/ruby/2.3.0/gems/activesupport-4.0.1/lib/active_support/core_ext/date_time/calculations.rb:161:in `<=>'

activesupport 4.0.1 and rals 4.0.1 are installed. I use chgems and I purged my .gem/ directory and Gemfile.lock before bundling again.

Here is a Gist of the User model.

And here is all of the backtrace output I could get from pry.

Random Generation of Items from Existing Model

I am fairly new to RoR and trying to get a basic app to work - I have a 'books' model and a 'genre' model. I wish to create a page that randomly generates books of different genre's for a user to select.

I have created a 'random_book' controller, but am unsure on how to proceed with the random selection and display.

Any help/pointers would be appreciated.

Thank you.

Authentication with Yahoo giving a connection Failure Error

I am using openid for social authentication like Yahoo, Flickr and google. Previously it the system was working fine but currently all time i m unable to sign in using yahoo and flickr and all time it is giving me connection_failure error.

in omniauth.rb i have this line

 provider :open_id, :store=> OpenID::Store::Filesystem.new('/var/tmp'),:name => 'yahoo', :identifier => yahoo.com'

and my link href is look like

 <%= content_tag(:li, link_to(:Yahoo, @user_to_be_registered.blank? ?
 "/auth/yahoo?openid_url=https://me.yahoo.com" : "#",:title=> t('.account_link_title', :acc_name=> "Yahoo"),:class=>"popup_auth",  :"data-width" => "500", :"data-height" => "500" )) %>

Read gujrati pdf in rails

I want to read a pdf file which is writen in gujrati language & write it in other pdf .So , how to achieve this in rails? I have no idea regarding this

Rails Engine: uninitialized constant User

My first question on stack overflow! I am trying to convert a rails app into an engine so that I can use it in my own Rails app.

I have converted everything to engine modules etc. (I'm still in my engine directory and haven't started implemented it yet in my rails app) but when I run rake db:migrate in the root I get the error:

rake aborted!
NameError: uninitialized constant User
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0    /gems/activesupport-4.2.6/lib/active_support/inflector/methods.rb:261:in `const_get'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0    /gems/activesupport-4.2.6/lib/active_support/inflector/methods.rb:261:in `block in constantize'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/inflector/methods.rb:259:in `each'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/inflector/methods.rb:259:in `inject'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activesupport-4.2.6/lib/active_support/inflector/methods.rb:259:in `constantize'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise.rb:292:in `get'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise/mapping.rb:81:in `to'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise/mapping.rb:76:in `modules'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise/mapping.rb:93:in `routes'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise/mapping.rb:160:in `default_used_route'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise/mapping.rb:70:in `initialize'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise.rb:326:in `new'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise.rb:326:in `add_mapping'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise/rails/routes.rb:238:in `block in devise_for'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise/rails/routes.rb:237:in `each'
/Users/matthijskolkman/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/devise-3.5.6/lib/devise/rails/routes.rb:237:in `devise_for'
/Users/matthijskolkman/Projects/customer_service_gem/brimir/config/routes.rb:2:in `block in <top (required)>'

I think it has to do with the routing, but not sure. Here are my routes:

Brimir::Engine.routes.draw do
  devise_for :users, controllers: { omniauth_callbacks: 'omniauth' }

  resources :users do
    get :tickets, to: 'tickets#index'
  end

  namespace :tickets do
    resource :deleted, only: :destroy, controller: :deleted
    resource :selected, only: :update, controller: :selected
  end

  resources :tickets, except: [:destroy, :edit] do
    resource :lock, only: [:destroy, :create], module: :tickets
  end

  resources :labelings, only: [:destroy, :create]

  resources :rules

  resources :labels, only: [:destroy, :update, :index, :edit]

  resources :replies, only: [:create, :new, :update, :show]

  get '/attachments/:id/:format' => 'attachments#show'
  resources :attachments, only: [:index, :new]

  resources :email_addresses

  resource :settings, only: [:edit, :update]

  root to: 'tickets#index'

  namespace :api do
    namespace :v1 do
      resources :tickets, only: [ :index, :show, :create ]
      resources :sessions, only: [ :create ]
      resources :users, param: :email, only: [ :create, :show ] do
        resources :tickets, only: [ :index ]
      end
    end
  end
end

And the user controller:

module Brimir
  class UsersController < ApplicationController
    include UsersStrongParams
    load_and_authorize_resource :user

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

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

      # if no password was posted, remove from params
      if params[:user][:password] == ''
        params[:user].delete(:password)
        params[:user].delete(:password_confirmation)
      end

      if current_user == @user
        params[:user].delete(:agent) # prevent removing own agent permissions
      end

      if @user.update_attributes(user_params)

        if current_user.agent? && current_user.labelings.count == 0
          redirect_to users_url, notice: I18n.translate(:settings_saved)
        else
          redirect_to tickets_url, notice: I18n.translate(:settings_saved)
        end

      else
        render action: 'edit'
      end
    end

    def index
      @users = User.ordered.paginate(page: params[:page])
      @users = @users.search(params[:q])
      @users = @users.by_agent(params[:agent] == '1') unless params[:agent].blank?
    end

    def new
      @user = User.new
    end

    def create
      @user = User.new(user_params)

      if @user.save
        redirect_to users_url, notice: I18n.translate(:user_added)
      else
        render 'new'
      end
    end

    def destroy
      @user = User.find(params[:id])
      @user.destroy
      redirect_to users_url, notice: I18n.translate(:user_removed)
    end
  end
end

Thanks in advance!

jeudi 21 avril 2016

Akami auth.net upgrade

I am using ActiveMerchant::Billing::AuthorizeNetGateway for authorize.net payment.

How can I upgrade for Akami and how can I change the URL ?

Rails same piece of code won't work with 3.2

So I have this on the erb:

<%= fields_for camera, :index =>camera.id do |field|%>
<%= field.check_box :alertflag %>

And this on the controller:

 @camera = Camera.update(params[:camera].keys, params[:camera].values)

And it works on one server which have Rails 3.0.9, but for some reason it doesn't work the same way on one server which have Rails 3.2.

How to format google autofill location selector?

On google location autofill how to format it to just City and Country.

For example, if Colombo selected it gives result as - Colombo, Western Province, Sri Lanka

I would like it to be Colombo , Sri Lanka

The same way if a user selects Colombo it should auto show Sri Lanka. Should I do this custom in back-end or can google autofill really handle something like this?

reference image

ruby on rails action mailer not receiving emails to arrays from a yaml file

I have an issue where i am able to send email via the mailer for a hardcoded array. But the email does not go through for an array picked up from config.yml

Here is my config.yml

company:
  email:
    - user1@company.com
    - User1.Lastname@company.com
    - User2.Lastname@company.com

This is my mailer class:

class ReportMailer < ActionMailer::Base
  default :from => "donotreply@company.com"


  def send_report(company, file)

      mail(:to=> "#{CONFIG[company]['email']}", :subject => "Daily  Report")
    end
  end
end

when run it in my rails console & view the logs, seems like everything was executed fine but I did not receive my email:

[DEBUG] 2016-04-21 18:21:29 :: Date: Thu, 21 Apr 2016 18:21:29 -0400
From: donotreply@merchantlink.com
to: ["user1@company.com", "User1.Lastname@company.com","User2.Lastname@company.com"]
 ...
 ...

 [INFO] 2016-04-21 18:21:29 ::
Sent mail to ["user1@company.com", "User1.Lastname@company.com", "User2.Lastname@company.com"]

If i change my code & replace it with hardcoded array instead of reading from config.yml it works fine.

Am i reading the yaml array wrong?

Rails 3 dynamic form errors in boostrap 3

I'm using #403 dynamic forms Railcast combined with twitter-boostrap-rails 3 and simpleform gems. I have some custom validations for the dynamic form. For example when one field its empty I use:

self.errors.add field, "can't be blank"

This is error can be showed iterating over object.errors.full_messages. The problem its than boostrap 3 doesn't add the proper css and doen't add the text field can't be blank under the input. What can be causing this issue?

Rails Won't Render My View

I'm running devise with custom views, and my login page was rendering perfectly before, but I just changed the name of the model from human to user, renamed the controller and the views, but it just refuses to render my view.

I don't get an error, my layout renders perfectly, but it doesn't yield the body for some reason.

Code

Here's my routes.rb for Users:

  ## devise controllers for users
  devise_for :user, controllers: {
    confirmations: 'user/confirmations',
    passwords: 'user/passwords',
    registrations: 'user/registrations',
    sessions: 'user/sessions',
    unlocks: 'user/unlocks',
    # commenting the below because omniauth gem isn't installed
    # omniauth_callbacks: 'user/omniauth_callbacks'
  }, skip: [:sessions]
  ## custom routes for users
  as :user do
    get 'login' => 'user/sessions#new', :as => :new_user_session
    post 'login' => 'user/sessions#create', :as => :user_session
    delete 'logout' => 'user/sessions#destroy', :as => :destroy_user_session
    get 'register' => 'user/registrations#new', as: :register
  end

Here's my sessions_controller generated by devise:

class User::SessionsController < Devise::SessionsController
  ...

  # GET /resource/sign_in
  def new
    super
  end
  ...
end

Here's my view:

<%= render layout: 'layouts/shared/left_logo_panel' do %>
  <%= form_for(resource, html: {class: 'form'}, as: resource_name, url: session_path(resource_name)) do |f| %>
    <div class="field form-group">
      <%= f.label :email %><br />
      <%= f.email_field :email, class:'form-control', autofocus: true %>
    </div>

    <div class="field form-group">
      <%= f.label :password %><br />
      <%= f.password_field :password, class:'form-control', autocomplete: "off" %>
    </div>

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

    <div class="actions">
      <%= f.submit "Log in", class:'btn btn-default' %>
    </div>
  <% end %>

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

Log

Started GET "/login" for 127.0.0.1 at 2016-04-21 04:48:13 -0700
Processing by User::SessionsController#new as HTML
  Rendered devise/shared/_links.html.erb (5.8ms)
  Rendered layouts/shared/_left_logo_panel.html.erb (9.4ms)
  Rendered user/sessions/new.html.erb within layouts/application (9.8ms)
  Rendered layouts/_shim.html.erb (0.0ms)
  Rendered layouts/_header.html.erb (0.3ms)
  Rendered layouts/_footer.html.erb (0.0ms)
  Rendered layouts/_ga.html.erb (0.1ms)
Completed 200 OK in 41ms (Views: 39.7ms | ActiveRecord: 0.0ms)

Image upload using carrierwave in show page

Using Rails 4 and Ruby 2.2,

I have book as model which should have image upload functionality in the show page of book. So User can create the book first and from show page upload the multiple images for book. I have used carrierwave as gem and have separate model created for Image.

image.rb

class Image < ActiveRecord::Base
  belongs_to :book

  mount_uploader :avatar, AvatarUploader
end

book.rb

class Book < ActiveRecord::Base
    belongs_to :subject, dependent: :destroy
    belongs_to :user, dependent: :destroy
    has_many :images, dependent: :destroy
end

books/show.html.erb

<%= form_for(Image.new, :html => { :multipart => true }) do |f| %>
   <div class="field">
     <%= f.label :name %><br>
     <%= f.text_field :name %>
     <%= hidden_field_tag "image[book_id]", @book.id %>
   </div>
   <%= f.fields_for :images do |p| %>
     <div class="field">
       <%= p.label :avatar %><br>
       <%= p.file_field :avatar, :multiple => true, name: "images[avatar]" %>
     </div>
   <%end%>

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

schema.rb

  create_table "images", force: :cascade do |t|
    t.datetime "avatar_updated_at"
    t.datetime "created_at",                    null: false
    t.datetime "updated_at",                    null: false
    t.integer  "book_id",           limit: 4
    t.string   "avatar",            limit: 255
    t.string   "name",              limit: 255
  end

  create_table "books", force: :cascade do |t|
    t.string   "title",       limit: 255
    t.integer  "page_number", limit: 4
    t.text     "description", limit: 65535
    t.datetime "created_at",                                null: false
    t.datetime "updated_at",                                null: false
    t.integer  "user_id",     limit: 4
    t.integer  "subject_id",  limit: 4
    t.boolean  "active",                    default: false
  end

Now I am kind of unable to proceed with this, can someone guide me on this because I am having form in books/show page and I need to show the image on the same page after successful updation of images.(Multiple images can be uploaded)

Thanks in advance

let me know if I need to provide any more information.

Rails Ajax Refresh Partial while persisting params

I have a Rails app with a controller/view called "calls". Here is the basic controller action for index:

calls_controller.rb

def index
    if params[:region].present?
      @assigned = Call.where(region_id: params[:region][:area]).assigned_calls.until_end_of_day
      @unassigned = Call.where(region_id: params[:region][:area]).unassigned_calls.until_end_of_day
   else
     @assigned = Call.assigned_calls.until_end_of_day
     @unassigned = Call.unassigned_calls.until_end_of_day
   end
  end

Here are my views:

index.js.erb

$('#active').html("<%= escape_javascript render :partial => 'calls/assigned_calls', :locals => {:assigned_calls => @assigned} %>");
$('#inactive').html("<%= escape_javascript render :partial => 'calls/unassigned_calls', :locals => {:unassigned_calls => @unassigned} %>"); 

$(".select").select2({
        placeholder: "Select One",
        allowClear: true
  });

index.html.erb

<div id="active">
  <%= render "assigned_calls" %>
</div>

<div id="inactive">
  <%= render "unassigned_calls" %>
</div>


<script>
$(document).ready(function() {
    setInterval(function () {
            $.ajax('calls/<%= params[:region][:area] %>');
    } , 5000);
});
</script>

_assigned_calls.html.erb (view code omitted)

<%= form_tag calls_path, :method => 'get' do %>
  <p>
<%= select_tag "region[area]", options_from_collection_for_select(Region.order(:area), :id, :area, selected: params[:region].try(:[], :area)), prompt: "Choose Region" %>
<%= submit_tag "Select", :name => nil, :class => 'btn' %>

So what's happening is on page load if I do not have the params of :region passed it sets the calls without being scoped by region. If region_id is present then it scopes calls where region_id is "1" or whatever the Region ID is that is passed from the submit_tag.

This works fine in the controller and view, however here's my problem. My index.html.erb I need to refresh the partials WITHOUT disturbing the params passed. So on setInterval I need to figure out how to reload the partials while persisting the params passed in the URL.

I tried to figure this out using a setInterval method but I'm not sure what I'm doing here 100%.

Can someone give me some advice on how to refresh the partials every 5 seconds while persisting the params so my instance variables persist through refresh?

If you need more context and/or code please let me know.

Rails - Get Params like "cart_item[price]=5%2C70" out of URL

My View make a redirect an pass the Params

?cart_item[price]=5%2C70€

. I try to get this with

@price = [:cart_item][:price]

, but there i get the error "can't convert Symbol into Integer". I try it with codes like ":cart_item_price" or ":cart_item.price" but always no variable was founded

How can i get this price in my other action ?

mercredi 20 avril 2016

How to update time according to each click on recently viewed properties

i want to list recently viewed properties in logged in users dashboard.

So that i created a table called recentview with 3 fields ie; user_id ,property_id and view_time(will enter the current view time in table on click on that property). I tried by below code. but problem is it is entering same record multiple times on each click on the same property . what i need is if i click one property that should enter in table once and in the next clicks on that same property the view_time of the same property record should update.

<% if current_or_null_user.recentviewed? property %>
   <a href = "<%=recentviews_path(:id => property.id)%>" data-method="post" ><div class="img-blocks" style="background-image:url(<%= property.image.url(:thumbnail)%>)"></div></a>
 <% else %>
   <a href = "<%=recentviews_path(:id => property.id)%>" data-method="post" >   <div class="img-blocks" style="background-image:url(<%= property.image.url(:thumbnail)%>)"></div></a>
<%end%>

on click on property the that current time, property_id and user_id is storing in database my controller

class RecentviewsController < ApplicationController
  before_action :authenticate_user!, except: :create
  def create
    if user_signed_in?
      @views = Recentview.where(user_id: current_user.id, property_id: params[:id],view_time: Time.now.strftime("%d/%m/%Y %H:%M")).first_or_create
      redirect_to :back
    else
      redirect_to new_user_session_path, alert: 'Please login/Sign up to add this property to your favourite.'
    end
  end
end

my model

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :properties  
  has_many :recentviews
  has_many :recentviewed_properties, through: :recentviews, source: :property  
  
  def recentviewed? property
    recentviewed_properties.include? property
  end
end
                               
                               
                               
class Recentview < ActiveRecord::Base
  belongs_to :user
  belongs_to :property
end
class Property < ActiveRecord::Base
        belongs_to :user
        has_many :recentviews
        mount_uploader :image, ImageUploader

end

Please give a a solution to solve this issue. How i will update view_time in each click, and also how i will avoid multiple entries of same property in recentviews table Any help is appreciatable