vendredi 30 septembre 2016

Email notification from ActionMailer using sendgrid when a user send a new message to another user

New to rails and Stackoverflow. learning the ropes and I'm building an application where I tried using ActionMailer to trigger an email to a user when a message has been sent. The problem is that my code sends a message to the user who wrote the message and not to the recipient.This is my message controller

here's the mailer.rb:

class ConversationMailer < ActionMailer::Base def conversation_created(user) mail(to: user.email, from: "contact@uvesty.com", subject: "You got a beloved message :D", body: "Hi, somebody has messaged you on"

end

end

undefined method 'paginate'

I am trying to use will_paginate gem but getting this error in title. I checked the thread below and did the changes but no luck

http://ift.tt/2dhPmkK

This is what i have

App/Controllers/books_controller.rb

class BooksController < ApplicationController
    def index
    #@books = Book.all
    @books = Book.paginate :page => params[:page], :per_page => 10
    end
end

index.html.erb:

<%= will_paginate @books %>

GemFile

gem 'will_paginate', '~> 3.0.4'

Enbironment.rb

gem 'will_paginate'

and this is the error i get:

undefined method `paginate' for #<Class:0x007fd539118a30>

uninitialized constant BooksController::Books

I am creating a sample app and trying to use will_paginate gem.

App/Controllers/books_controller.rb

class BooksController < ApplicationController
    def index
    #@books = Book.all
    @books = Books.paginate :page => params[:page], :per_page => 10
    end
end

App/views/index.html.erb

<% for book in @books do %>
  <h2><%=h book.title %></h2>
  <p><%= book.thoughts %></p>
  <%= will_paginate @books %>
<% end %>

when i load application i get the error in title. am i missing something?

Is there any alternative of in operator in where clause for active record query in rails

sql query for my rails query is given below... When I m running query indiviually for each destination id ,total time is less compare to if I run it with in operator. SELECT DISTINCT requested_trips.id FROM requested_trips INNER JOIN requested_trips_destinations ON requested_trips_destinations.requested_trip_id = requested_trips.id INNER JOIN destinations ON destinations.id = requested_trips_destinations.destination_id WHERE (requested_trips.status = 'Active' and requested_trips.trip_stage = 4 and (destinations.id in (64,100,545,...)))

How to add multiple classes and attributes to rails button_to?

I'm quite new to rails and I was trying somehow add all the attributes and classes I have into the button_to within the button_to because at the moment it's adding a silver button box on top of my actual button, so I don't know how to actually combine the multiple classes above within it.

   <button class="class1" data-method="download" data-option="download" type="button" title="Download">
        <span class="class2" data-toggle="tooltip" data-placement="bottom" title="Download">
                <span class="icon">
                    <%= button_to proof_path(@param) %>
                </span>
        </span>
    </button>

link_to won't work because I want the actual button to be clickable and not text.

Any suggestions?

Render js if variable length is 0 (rails)

I am defining a variable in my controller method. I want to render js if the size of the variable is zero.

My code is:

def department
  @department = Department.all
end

I want or do something like this:

def department
  @department = Department.all
  if @department.count > 0
    render :html => html-template-name
  else
    render :js => "alert('No department available');"
  end
end

What should be the syntax of render html part?

How to take value for Object result in ruby on rails

I want to print specific value from object result. here is i am execute SQL query and take all data from View tables, All data coming from "Employee_Information" view(table). hr_controller.rb

class HrController < ApplicationController

  def internal_employee_page        
    @employees = MysqlConnection.connection.select_all("SELECT * FROM Employee_Information")
  end 
end

internal_employee_page.html.erb this is my first view

<div id="job_details">
    <% @employees.each do |emp| %>
        <%= render partial: "hr/employee_details", locals: {emp: emp} %>
    <% end %>               
</div>

_employee_details.html.erb this is my second view

<h3> User Name : <%= emp%> </h3>

like this I am trying to print all value then I got following result enter image description here I want to print each value I tried this also in my second view

<h3> User Name : <%= emp.full_name%> </h3>

But I got Error: enter image description here Please help me I tried every thing according to my knowledge, where am I wrong and what is problems

Cant Send email from outlook using ruby script

so this is code works fine with yahoo and gmail but it throws an error when i run it with using outlook smtp

  `require 'mail'



   options =   { 
           :address        => 'smtp.live.com',
           :port           => '587',
           :authentication => :login,
           :user_name      => ENV['mymail@outlook.com'],
           :password       => ENV['mypassword'],
           :enable_starttls_auto => true
                   }




Mail.defaults do
delivery_method :smtp, options
end



Mail.deliver do

to 'test@gmail.com'
from 'mymail@outlook.com'
subject 'test'
body 'outlook'
end

`

when i execute this script it gives me "untitled.rb: end of file reached (EOFError)" this error ,i would really appreciate your help

jeudi 29 septembre 2016

undefined method `resources' for nil:NilClass

I am learning Ruby on Rails and trying to create a sample app. I have created the following files:

app/controllers/books_controller.rb

class BooksController < ApplicationController
    def index
    @books = Book.all
    end
end

app/models/book.rb

class Book < ApplicationRecord
end

config/routes.rb

Rails.application.routes.draw do |map|
    map.resources :books
end

I am using ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin14] and rails 5.0.0.1 versions.

Why I am getting error undefined method 'resources' for nil:NilClass?

How to set an optional reset_password_keys for Devise

In a Rails app, the config Devise file has a reset_password_keys option. Is there a way to make one of the keys optional?

Currently I have this setting config.reset_password_keys = [ :email, :account_id ].

I would like to make the :account_id an optional key if there is no account_id present.

How to add single method to handle multiple routes

my rails application is a proxy server for some rest API services It means all the request for the rest server is routing through my rails app. I have defined all require routes in my routes.rb file and I have written different methods for each routes in my controller. So instead of different methods for each route I want a single method in my controller where I can check the request.fullpath and based on request parameters redirect it to appropriate rest service call

Here is my routes look like

  get '/lookup/location/search', to: 'ticketing#lookup_location_search'
  get '/lookup/company/search', to: 'ticketing#lookup_company_search'
  get '/lookup/assignmentGroup/search', to: 'ticketing#lookup_assignment_group_search'
  get '/lookup/ci/search', to: 'ticketing#lookup_ci_search'
  get '/lookup/user/search', to: 'ticketing#lookup_user_search'  

For each route there is a separate method exist in controller instead of that i want a single method which would further call correct rest URL based on request parameters

how to render template use liquid gem with html, css file and asset

I have a folder with html file, css and asset. forder tree like below:

enter image description here

Forder ifreezeapp in folder public

When i try parse and render file index.html in view

Liquid::Template.parse( File.read("#{Rails.root.to_s}/public/ifreezeapp/index.html") ).render().html_safe  

But it load incorrect assets,css,js....

How to render template with can load correct assets,css,js,...

mercredi 28 septembre 2016

ArgumentError (wrong number of arguments (given 0, expected 1))

I am upgrading my rails application from Rails 3.2.1 to Rails 4.0.0.

has_many :paid_projected_images, :source=> :projected_images, :through => :paid_salon_entries, :readonly=> false

If i remove readonly: false than this association is working fine in rails 4 but if i add readonly to this scope than it is giving me ArgumentError (wrong number of arguments (given 0, expected 1))

any idea??

Rails Engine Controller Test

I have a rails engine that I've created to share Model code between two repositories. Their respective controllers live in their respective repositories. I'm trying to test the controllers, using the machinist gem to generate the factories. But when I try to create my factories I get an uninitialized Constant error, which signifies to me that the models from my rails engine aren't getting properly required. I tried to explicitly require the rails engine gem in my spec_helper.rb file, but I got a file not found error then.

Curious if anyone has dealt with this before?

What to do with error 'Please review the problems below:' using cocoon gem?

I am creating an ruby on rails 5 application. It is a todolist kind of application and using simple_form, haml-rails and cocoon gem. This is a application with nested form.

  1. Generated a scaffold for goal and created model for action Goal.rb and Action.rb

    class Goal < ApplicationRecord
      has_many :actions
      accepts_nested_attributes_for :actions, reject_if: :all_blank
    end
    
    class Action < ApplicationRecord
      belongs_to :goal
    end
    
    
    1. Then added the actions_attribute to permit in the params
class GoalsController < ApplicationController   before_action :set_goal, only: [:show, :edit, :update, :destroy]   def index
    @goals = Goal.all   end   def show   end   def new
    @goal = Goal.new   end   def edit   end   def create
    @goal = Goal.new(goal_params)
    respond_to do |format|
      if @goal.save
        format.html { redirect_to @goal, notice: 'Goal was successfully created.' }
        format.json { render :show, status: :created, location: @goal }
      else
        format.html { render :new }
        format.json { render json: @goal.errors, status: :unprocessable_entity }
      end
    end   end   def update
    respond_to do |format|
      if @goal.update(goal_params)
        format.html { redirect_to @goal, notice: 'Goal was successfully updated.' }
        format.json { render :show, status: :ok, location: @goal }
      else
        format.html { render :edit }
        format.json { render json: @goal.errors, status: :unprocessable_entity }
      end
    end   end   def destroy
    @goal.destroy
    respond_to do |format|
      format.html { redirect_to goals_url, notice: 'Goal was successfully destroyed.' }
      format.json { head :no_content }
    end   end   private
    def set_goal
      @goal = Goal.find(params[:id])
    end
    def goal_params
      params.require(:goal).permit(:name, :purpose, :deadline, actions_attributes: [:step])
    end

end

  1. Forms for both form.html and action.html

_form.html.haml

= simple_form_for(@goal) do |f|
  = f.error_notification

  .form-inputs
    = f.input :name
    = f.input :purpose
    = f.input :deadline
    %h3 Actions
    #tasks
      = f.simple_fields_for :actions do |action|
        = render 'action_fields', f: action
      .links
        = link_to_add_association 'Add', f, :actions

  .form-actions
    = f.button :submit

// action.html.haml
.nested-fields = f.input :step = f.input :done, as: :boolean = link_to_remove_association "remove task", f

log in the console when i submit form

Started POST "/goals" for ::1 at 2016-09-28 21:21:48 +0530
Processing by GoalsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"GEjMM1ntPTj29+5rBPvnQ9EKnx1umS+KjyQ1DwK0attazr4ij/OBaOqR2KI8J0t6keotTQgR9r393lB+ximrGQ==", "goal"=>{"name"=>"Raja", "purpose"=>"asdfasd", "deadline"=>"asdfasdf", "actions_attributes"=>{"0"=>{"step"=>"Rajasdfsdfsdwead", "done"=>"0", "_destroy"=>"false"}, "1"=>{"step"=>"ewerqsdfd", "done"=>"0", "_destroy"=>"false"}}}, "commit"=>"Create Goal"}
Unpermitted parameter: done
Unpermitted parameter: done
   (3.0ms)  BEGIN
   (1.0ms)  ROLLBACK
  Rendering goals/new.html.haml within layouts/application
  Rendered goals/_action_fields.html.haml (30.5ms)
  Rendered goals/_action_fields.html.haml (27.0ms)
  Rendered goals/_action_fields.html.haml (30.5ms)
  Rendered goals/_form.html.haml (371.8ms)
  Rendered goals/new.html.haml within layouts/application (450.3ms)
Completed 200 OK in 1597ms (Views: 1431.2ms | ActiveRecord: 4.0ms)

Warbler gem: SystemStackError: stack level too deep

I am trying to create war file of jruby on rails application. i have installed warble gem and inside of my rails application directory i am executing command warble but it's giving me below error. please help me in knowing why i am getting this error.

warble aborted! SystemStackError: stack level too deep /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:in initialize' /home/administrator/Desktop/imaging-resource-planning/Rakefile:7:in(root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:inload_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:inproject_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:ininitialize' config/warble.rb:1:in (root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:ininitialize' config/warble.rb:0:in initialize' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:in load_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:in project_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:in initialize' /home/administrator/Desktop/imaging-resource-planning/Rakefile:7:in(root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:in initialize' config/warble.rb:1:in(root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:inload_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:inproject_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:ininitialize' config/warble.rb:0:in initialize' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:ininitialize' /home/administrator/Desktop/imaging-resource-planning/Rakefile:7:in (root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:in load_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:in project_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:in initialize' config/warble.rb:1:in(root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:in initialize' config/warble.rb:0:ininitialize' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:inload_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:inproject_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:ininitialize' /home/administrator/Desktop/imaging-resource-planning/Rakefile:7:in (root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:ininitialize' config/warble.rb:1:in (root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:in load_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:in project_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:in initialize' config/warble.rb:0:ininitialize' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:in initialize' /home/administrator/Desktop/imaging-resource-planning/Rakefile:7:in(root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:inload_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:inproject_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:ininitialize' config/warble.rb:1:in (root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:ininitialize' config/warble.rb:0:in initialize' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:in load_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:in project_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:in initialize' /home/administrator/Desktop/imaging-resource-planning/Rakefile:7:in(root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:in initialize' config/warble.rb:1:in(root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:inload_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:in load' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:inproject_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:ininitialize' config/warble.rb:0:in initialize' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:ininitialize' /home/administrator/Desktop/imaging-resource-planning/Rakefile:7:in (root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:240:in load_dependency' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:268:inload' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:62:in load_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/application.rb:59:inload_project_rakefile' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler.rb:26:in project_application' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits/rails.rb:27:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:in before_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/traits.rb:29:inbefore_configure' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/config.rb:213:in initialize' config/warble.rb:1:in(root)' /home/administrator/.rvm/gems/jruby-1.7.16@IRP_NEW/gems/warbler-1.4.9/lib/warbler/task.rb:46:in `initialize' (See full trace by running task with --trace)

mardi 27 septembre 2016

view is not updating after applying filter [ruby rails filterrific]

I have a simple table which displays all the users and its attributes id,name,age,status,location. I want to filter on age and status.

Id name age status location
1  xz    22  single  ca
2  yy    23  married ma

I am using filterrific plugin and able to display the list and the filter dropdown.

My user.rb

 filterrific(
    available_filters: [
      :with_status,
      :with_age
    ]
  )

  scope :with_age, lambda { |age|
    where(age: [*age])
  }

  scope :with_status, lambda { |status|
    where(status: [*status])
  }


  def self.options_for_select
    order('LOWER(status)').map { |e| [e.status] }.uniq
  end
  def self.options_for_select2
    order('LOWER(age)').map { |e| [e.age] }.uniq
  end

The controller index looks like

def index
    @filterrific = initialize_filterrific(
      User,
      params[:filterrific],
      select_options: {
        with_status: User.options_for_select,
        with_clearance_batch_id: User.options_for_select2
      },
      default_filter_params: {},
      available_filters: [],
    ) or return

    @users = @filterrific.find
    respond_to do |format|
      format.html
      format.js
    end

  end

the index.html.erb looks like

<%= form_for_filterrific @filterrific do |f| %>

  <div>
    age
    <%= f.select(
      :with_age,
      @filterrific.select_options[:with_age],
      { include_blank: '- Any -' },
      {class: 'form-control' }
    ) %>
  </div>
  <div>
    status
    <%= f.select(
      :with_status,
      @filterrific.select_options[:with_status],
      { include_blank: '- Any -' },
    ) %>
  </div>

<% end %>

<%= render(
  partial: 'browse_users/list',
  locals: { users: @users }
) %>

When I go to the page I am able to see all the users. Now when I filter nothing happens. I still see all the users. Not sure what is happening. I have feeling that my scope filter is not getting applied.

Ruby on rails uri.parse is not recognizing local host

Hello I am trying to run this code require "net/http" require "uri" uri = URI.parse("http://localhost:3000/stms_time/") response = Net::HTTP.post_form(uri, 'commit'=>'Submit', 'userid'=>'username', 'env'=>'env','password'=>'pwd')

all I get is garbage. Could you help me solve this issue .

rake db:create throwing LoadError: cannot load such file

I am totally new to ruby and currently setup a framework which was written in ruby.

While configuring it starts failing when I launch the below command

rake db:create

rake aborted!
LoadError: cannot load such file -- active_support/security_utils
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.1.10/lib/active_support/dependencies.rb:247:in `require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.1.10/lib/active_support/dependencies.rb:247:in `block in require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.1.10/lib/active_support/dependencies.rb:232:in `load_dependency'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.1.10/lib/active_support/dependencies.rb:247:in `require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/actionpack-4.1.15/lib/action_controller/metal/http_authentication.rb:2:in `<top (required)>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/actionpack-4.1.15/lib/action_controller/base.rb:228:in `<class:Base>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/actionpack-4.1.15/lib/action_controller/base.rb:164:in `<module:ActionController>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/actionpack-4.1.15/lib/action_controller/base.rb:5:in `<top (required)>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/gon-5.2.3/lib/gon/helpers.rb:59:in `<top (required)>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.1.10/lib/active_support/dependencies.rb:247:in `require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.1.10/lib/active_support/dependencies.rb:247:in `block in require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.1.10/lib/active_support/dependencies.rb:232:in `load_dependency'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/activesupport-4.1.10/lib/active_support/dependencies.rb:247:in `require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/gon-5.2.3/lib/gon.rb:10:in `<top (required)>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/bundler-1.13.1/lib/bundler/runtime.rb:91:in `require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/bundler-1.13.1/lib/bundler/runtime.rb:91:in `block (2 levels) in require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/bundler-1.13.1/lib/bundler/runtime.rb:86:in `each'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/bundler-1.13.1/lib/bundler/runtime.rb:86:in `block in require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/bundler-1.13.1/lib/bundler/runtime.rb:75:in `each'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/bundler-1.13.1/lib/bundler/runtime.rb:75:in `require'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/bundler-1.13.1/lib/bundler.rb:106:in `require'
/home/ubuntu/open-source-billing/config/application.rb:9:in `<top (required)>'
/home/ubuntu/open-source-billing/Rakefile:5:in `require'
/home/ubuntu/open-source-billing/Rakefile:5:in `<top (required)>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/rake_module.rb:28:in `load'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/rake_module.rb:28:in `load_rakefile'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/application.rb:689:in `raw_load_rakefile'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/application.rb:94:in `block in load_rakefile'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/application.rb:176:in `standard_exception_handling'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/application.rb:93:in `load_rakefile'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/application.rb:77:in `block in run'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/application.rb:176:in `standard_exception_handling'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/lib/rake/application.rb:75:in `run'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/gems/rake-11.1.2/bin/rake:33:in `<top (required)>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/bin/rake:23:in `load'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/bin/rake:23:in `<main>'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/bin/ruby_executable_hooks:15:in `eval'
/home/ubuntu/.rvm/gems/ruby-2.0.0-p648/bin/ruby_executable_hooks:15:in `<main>'

While running the command rake db: create getting below error

Help would be appreciated. Thanks

Using Rails 3.2.22 and Mongoid 2.5.1 with Mongo 3.2

I am attempting to upgrade our legacy rails/mongo application. Our production Mongodb is 2.4 and we would like to upgrade to 3.2 and still use Mongoid. We use auth on the development database as follows

mongo <host> -usome_user -psome_pwd --authenticationDatabase "some-database"

The Mongoid.yml file for Mongoid 2.5.1 doesn't seem to have the ability to pass the authentication database parameter, and the authentication fails when trying to perform a rake command, or even get into the rails console.

So my question is this, IS there a way to set the default authentication database so that this parameter does not need to be passed along? If not, then is there a way I can edit my 2.5.1 mongoid.yml so include this information? I am guessing the I will have to upgrade the whole nine yards to a version of Mongoid which can support Mongodb 3.2

Below is the pertinent part of the YML file: development: <<: *defaults hosts: - - - - port: database: username: password:<%= SOME_CREDENTIALS[:mongo][:password] %> max_retries_on_connection_failure: 1

undefined method `[]' for nil:NilClass for .hbs file

I am upgrading my rails application from 3.2.1 to 4.2.0. It is very big application. I am using handlebars_assets gem for .hbs file. if i include .hbs views in my application.js file it is giving me undefined method `[]' for nil:NilClass.

Rails, redirect work in development but not in production

I have a simple form for login, and I want to redirect to admin/index if the login is successful. This works in development but not in production. My production.log says nothing about this, just:

I, [2016-09-27T12:41:53.504340 #7503] INFO -- : Started POST "/login" for 127.0.0.1 at 2016-09-27 12:41:53 +0300 I, [2016-09-27T12:41:53.506417 #7503] INFO -- : Processing by AdminController#login as JS I, [2016-09-27T12:41:53.506698 #7503] INFO -- : Parameters: {"utf8"=>"✓", "admin"=>{"username"=>"testusername", "password"=>"[FILTERED]"}} I, [2016-09-27T12:41:53.618386 #7503] INFO -- : Redirected to http://localhost:3000/admin/index I, [2016-09-27T12:41:53.618978 #7503] INFO -- : Completed 200 OK in 112ms (ActiveRecord: 9.2ms)

I although get a wierd reponse to my login post on firebug:

Turbolinks.clearCache()

Turbolinks.visit("http://localhost:3000/admin/index", {"action":"replace"})

I dont know what that means but could it be that I got a problem with my turbolinks??

Here is my form:

<%= form_for(:admin,:remote => true, :html => {id: 'form-signin', class: 'form-signin'}, :url => 'login') do |f| %>

        <div class="popup-header">

            <span class="text-semibold">Administrator Login</span>

        </div>
        <div class="well">
            <div class="form-group has-feedback">
                <label>Username</label>
                <%= f.text_field :username, class: 'form-control',:html => { type:'text',  name: 'username', required: "", autofocus: ""}, :placeholder => "Username"%>
                <i class="icon-users form-control-feedback"></i>
            </div>

            <div class="form-group has-feedback">
                <label>Password</label>
                <%= f.password_field :password, class: 'form-control', :html => {type:'password', name: 'password', required: ""}, :placeholder => "Password" %>
                <i class="icon-lock form-control-feedback"></i>
            </div>

            <div class="row form-actions">

                <div class="col-xs-6">
                    <button type="submit" class="btn btn-warning pull-right"><i class="icon-menu2"></i> Sign in</button>
                </div>
            </div>
        </div>
        <% end %>
</div>  

And the my Admin_controller:

class AdminController < ApplicationController

def index
    respond_to do |format|
        format.js
    end
end

def login
  if params[:admin][:username].present? && params[:admin][:password].present?
    found_user = Admin.where(:username => params[:admin][:username]).first
      if found_user

        authorized_user = found_user.authenticate(params[:admin][:password])
        session[:admin]=params[:admin][:username]
      end
  end
  if authorized_user
    redirect_to admin_index_path     
  else      
    respond_to do |format|
            format.js {render :action => 'wrong_credentials'}
    end
  end
end

def destroy #LOGOUT FUNCTION
  session[:admin] = nil
  redirect_to :controller => 'admin', :action => 'login_page'
end
end

And my routes

 Rails.application.routes.draw do
  root 'admin#login_page'

  get '/init' => 'api#api_init'

  get '/admin/index', to: 'admin#index', :as => 'admin_index'
  post '/login' => 'admin#login', :as => 'admin_login'
  controller :admin do
  get 'index' => :index
  get  'login' => :new
  post 'login' => :create
  delete 'logout' => :destroy
  end

end

Any help appreciated. Thanks for reading.

using filterrific gem to filter table by column

I have a simple user table on which I want to filter by two attributes. The user attributes consists of Id,name,age,status,location and I want to allow filter by both age and status. I followed filterrific instructions but got lost and messed up.

In my model user.rb I added

filterrific :available_filters => %w[
                with_age
                with_status
              ]

scope :with_age, lambda { |ageNumber|
  where(:age => [*ageNumber])
}
scope :with_status, lambda { |status|
  where(:status => [*status])
}

then in my controller I added

def index
    @filterrific = initialize_filterrific(
      User,
      params[:filterrific],
      select_options: {
        with_age: User.options_for_select,
        with_status: User.option_for_select2,
      },
      persistence_id: 'shared_key',
      default_filter_params: {},
      available_filters: [],
    ) or return

    @users = @filterrific.find.page(params[:page])
  end

def self.options_for_select
  order('LOWER(age)').map { |e| [e.age, e.age] }
end

def self.options_for_select2
  order('LOWER(status)').map { |e| [e.status, e.status] }
end

In my view

<%= form_for_filterrific @filterrific do |f| %>

  <div>
    status
    <%= f.select(
      :with_status
      @filterrific.select_options[:with_status],
      { include_blank: '- Any -' }
    ) %>
  </div>
  <div>
    age
    <%= f.select(
      :with_age
      @filterrific.select_options[:with_age],
      { include_blank: '- Any -' }
    ) %>
  </div>

<% end %>

How to Upgrade very big application from rails 3.2.0 to rails 4.2.1

I am working on very big application which is build in rails 3.2.0. Now i want to upgrade that to rails 4.2.1.

After updating all gems (using bundle update).. I am facing lot of issues like scope is not callable ,some gems compatible error and devise - form is not working.

What is the best way to upgrade rails application??

lundi 26 septembre 2016

Rails default exception handling for JSON

By default Rails serves a helpful HTML page for 404 Resource Not Found and 500 Internal Server Error. But for my JSON API I'd like to serve JSON-formatted replies.

I don't want a solution that requires per-controller implementations, this should be default exception handling for all API requests.

can't make rails assets pipeline to works?

i am developing an app in rails with some css and js plugins template, by default we should separate or js and css file into javascript and css folder right?

but the problem is my plugins folder structure are quite complex, have a lot of sub folders, so i decided to put all the assets (css, js, images, fonts) into a folder, the problem is everything not working on production mode, the css styles, scripts, images all not loaded, please help.

here is my structure :

javascripts
stylesheets
public_assets
  - img
    - icon
    - bg
    - favicon
    - images
      - proteam
    - png
      - ualanding
    - portofolio
      - fullsize
      - thumbnail
  - font
  - css
  - js
  - sass
  - vendor
    - ninja-slider
    - bootstrap
      - font
      - css
      - js
    - font awesome 
      - css
      - fonts
      - less
      - scss
    - jquery
    - magnific-popup
    - scroolreveal
  - vid
images
Static_Dev

FYI i already run

rake assets:precompile

command

i reference my images mostly like these :

<img alt="UrbanAce" src="assets/img/logo.png" height="24">

i believe when i run on production mode, the assets path changed, so i changed my image tag to :

<%= image_tag "logo.png", { src: "logo.png", height: "24"} %>

the above code did not work, even in development mode.

also, what if i need to call some background images from css? something like

 .hero {
  background-image: url("../img/png/UA-Landing/UA-Pattern.png");
  background-repeat: repeat-x;
  background-position: 0 76px;
  height: 280px;
}

how should i replace it? so it will work on production and development mode.

many thanks....

Ensure to run code after rails `delayed job` fails or successess

Is there any way we can ensure certain code to run event after the delayed job is failed or succeeds just like we can write ensure block in exception handling?

How to set DNS to my IP and port - Atlantic.Net

enter image description hereI'm new to host my ruby on rails application on the server. I have bought a server from Atlantic.Net and running my project on a port let's say port-3001. Now I'm unable to set my domain to my IP and a specified port. Please suggest anyone what and how to do... ?

dimanche 25 septembre 2016

I cant gem install cocoapods, its crash

/Users/RaInVis/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/path_support.rb:25:in `initialize': wrong number of arguments (given 0, expected 1) (ArgumentError)

when i gem install cocoapods in terminal, it show me wrong, I do not know how to do, please help me ,thank you!

Gem 'sitemap', running rake on server?

I need to create sitemap file, so I found interesting gem 'sitemap'. I have deployed my app with capistrano. And already users have created a lot of posts.

So, I did everything gem is told me to do. I configured sitemap.rb and run rake sitemap:generate. But the I look at generated file, and it have map of my local version of app (obviously). So I loaded ready sitemap.rb file to server. But I can't run rake command on server, it giving me:

rake aborted!
Gem::LoadError: You have already activated rake 10.4.2

And I don't understand how can I run rake command on my server.

How to do each do on an active record relation results and store it in a variable which should be used for pagination

I'm facing a problem needed help I had a variable with results of a method and that variable class is active record relation and now I need to perform each do on that variable so that I can perform some if else conditions and store the results which should be sent to rabl file

I used array variable for storing final results which will be sent to rabl file but it's giving error like undefined method current page for array

But I dont want to add will_paginate/array

I want result of the each condition appended to an variable and that variable class should be active record relation is it possible to do

Note: in each condition I need to perform association also

How to add a background image by jQuery? (Ruby on Rails)

enter image description here

Why doesn't the above code work? I have also tried puting the image file in the images directory, or using different kinds of url path like url("1.png"), url(../images/1.jpg), or url(app/assets/javascripts/1.png), neither worked (and I tried background-imagetoo!).

By the way it works when I tried an image located on the Internet (the link in the comment block in the above image)

self.search body Rails

In Rails I'm trying to create an additional Search field for a Articles project in which the 2nd search field searches the Articles Body and not the Title!

Look at the project here http://ift.tt/2d0H2pH

index.html.erb

    <div id="main">
     <%= form_tag articles_path, :method => 'get' do %>
      <%= text_field_tag :search, params[:search], class: "form-control", placeholder: "Search Title" %><br><div>
       <%= submit_tag "Search", :name => nil, class: "btn btn-success" %>
        <% end %>

     <%= form_tag articles_path, :method => 'get' do %>
      <%= text_field_tag :body, params[:body], class: "form-control", placeholder: "Search Body" %>
       <%= submit_tag "Search", :name => nil, class: "btn btn-success" %>
        <% end %>

Article.rb

    def self.search(query)
     # where(:title, query) -> This would return an exact match of the query
       where("title like ?", "%#{query}%")
    end

ArticlesController.rb

    def index

     @articles = Article.all
     @markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML)

    # Adding search feature for Title.
      if params[:search]
         @articles = Article.search(params[:search]).order("created_at DESC")
      else
         @articles = Article.all.order('created_at DESC')
      end
    end

I've searched through these Stack Posts but can't seem to find an answer(I would have posted more but because my reputation is low I can only post two links.)

Search in Rails ==> But it only talks about getting the search to work correctly for the title, no mention of the body

http://ift.tt/2d0Knom ==> This one sorta had what I was looking for but this is more about prices and other parameters, not simply searching for through another column of the row; searching Body instead of Title.

I've tried adding different methods to the Article.rb model, Articles_controller.rb, but I'm just shooting in the dark; any suggestions stack family?

Your help would be greatly appreciated! Thanks! =)

samedi 24 septembre 2016

Sqlite db entries vanishing

I am building a Ruby on Rails web app and I am using the sqlite database. When I insert something in database, it adds those entries in the database. Whenever I stop the server and again runs it, the entries vanish.

Could someone please tell me what might be the problem?

I am very new to ruby on rails development.

Incredibly odd iOS 10 site visit and logging issues

Im not even sure how to begin to be honest. One of my sites is a very populate education website. We log all site visits, the ip address, referrer and other information for tracking and affiliate payouts.

On 9/14 we saw a HUGE spike in our internal numbers for direct traffic. It's not reflected in Google Analytics, but it's in our logs.

Upon further investigation, we were able to isolate ALL of the traffic to a single user agent:

Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A403 Safari/602.1

So as soon as iOS 10 came online, we saw this odd massive spike. Logically (and according to GA) there was no reason why iOS 10 should become this massive source of traffic bringing in orders of magnitude more direct traffic.

When we dove further, we discovered something else. If we look at the IP Address count for any day after the 14th and for traffic from the above user agent (iOS 10) we see things like this:

ip_address | count -----------------+------- 73.178.228.81 | 72 104.231.85.1 | 48 73.219.188.93 | 44

but if we look at ANY OTHER user agent, iOS 9.3.5 for example, we see normal traffic:

ip_address | count -----------------+------- 68.100.68.242 | 11 141.239.187.223 | 7 70.211.8.103 | 6

This is completely stumping us. Does anyone have ANY IDEA why traffic from Safari in iOS 10 could produce different results than any other version before it?

vendredi 23 septembre 2016

Async task failing on ruby worker. I want to send directly

Hi I have used async task to send emails and sms from my ruby server in the past.

This is not working

 def notify_customer_create
SendEmailWorker.perform_async('EstimationMailer', 'new_estimation', self.id)

 end

This is working

def notify_customer_create
  EstimationMailer.new_estimation(self.id).deliver

 end

So i got around it. But now i am facing problem to send sms the same way.

Here is the code i have:

def send_on_create_confirmation_instructions
 unless self.guest
  phone_number = self.mobile_phone.number
  self.update_attribute(:confirmation_sent_at, Time.now)
  SendSecretCodeWorker.perform_async(phone_number, self.confirmation_token)
end
 end

Here is the definition:

 class SendSecretCodeWorker
  include Sidekiq::Worker
  sidekiq_options retry: false
  def perform(number, code)
MobileOperator.send_code(number, code)
  end
end

Somehow perform_async doesnt work. How to send it without using "async" as i did for emails?

jeudi 22 septembre 2016

Getting server error 500 on calling a method ruby

Hi when i call a function i get the following error log. Please help decipher it.

NoMethodError (undefined method `first' for #<Matching:0x0000000875a050>):
  app/mailers/matching_mailer.rb:6:in `new_matchings_for_customer'
  app/models/matching.rb:133:in `block in create_matchings_from_service'
  app/models/matching.rb:126:in `each'
  app/models/matching.rb:126:in `create_matchings_from_service'
  app/models/matching.rb:30:in `process_matchings_for_service'
  app/models/payments/subscription.rb:94:in `find_matchings'
  app/models/payments/subscription.rb:85:in `after_create_actions'
  app/controllers/contractors/subscriptions_controller.rb:51:in `subscribe'
  app/controllers/contractors/subscriptions_controller.rb:19:in `create'

1

Ruby Array Elements Merging

just wondering if there're other alternatives to merging elements in an array from

[ ["time","Oct-1-2016"], ["message","test message"], ["host","localhost"] ]

to

["time=Oct-1-2016","message=test message","host=localhost"]

I've got it nailed down toarray.map {|k,v| "#{k}=#{v}"} and just wondering if there are any other ways of achieving the above without using the map function? Thanks yo!

I'm Getting error "unknown attribute 'user_id' for Assignment"

I have researched this error but couldn't find a answer that works for me.

The Error

ActiveRecord::UnknownAttributeError in AssignmentsController#new

 def new
     @assignment = current_user.assignments.build
   end  

   def create


Controller - assignments_controller.rb :

    class AssignmentsController < ApplicationController
  before_action :authenticate_user!
  before_filter :admin_access, only: [:new, :create, :edit, :update, :destroy]


    def index
     @assignments = Assignment.all
    end


   def show
     @assignment = Assignment.find(params[:id])
   end

   def new
     @assignment = current_user.assignments.build
   end  

   def create
     @assignment = current_user.assignments.build
     @assignment.name = params[:assignment][:name]
     @assignment.description = params[:assignment][:description]
     @assignment.picture = params[:assignment][:picture]

     @assignment.public = params[:assignment][:public]

     if @assignment.save
       flash[:notice] = "Assignment was saved successfully."
       redirect_to @assignment
     else
       flash.now[:alert] = "Error creating assignment. Please try again."
       render :new
     end
   end

     def edit
     @assignment = Assignment.find(params[:id])
     end

      def update
     @assignment = Assignment.find(params[:id])

     @assignment.name = params[:assignment][:name]
     @assignment.description = params[:assignment][:description]
     @assignment.picture = params[:assignment][:picture]

     @assignment.public = params[:assignment][:public]

     if @assignment.save
        flash[:notice] = "Assignment was updated successfully."
       redirect_to @assignment
     else
       flash.now[:alert] = "Error saving assignment. Please try again."
       render :edit
     end
      end

   def destroy
     @assignment = Assignment.find(params[:id])

     if @assignment.destroy
       flash[:notice] = "\"#{@assignment.name}\" was deleted successfully."
       redirect_to action: :index
     else
       flash.now[:alert] = "There was an error deleting the assignment."
       render :show
     end
   end

     private 

     def assignment_params
         params.require(:assignment).permit(:name, :description, :picture)
     end
end

Model - 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
    validates_uniqueness_of :username 
  has_many :articles
  has_many :submits
  has_many :comments 
  has_many :assignments

end

Model - assignment.rb :

class Assignment < ActiveRecord::Base
        has_many :submits, dependent: :destroy
        belongs_to :user
end

views

index.html.erb:

  <div class="col-lg-12 text-center">
<h1>Assignments 

    <% if current_user.admin %>
     <%= link_to "New Assignment", new_assignment_path, class: 'btn btn-success' %>
     <% end %>

</h1>
  </div>
        <hr>

 <div class="row">
   <div class="col-md-8">
 <!-- #7 -->
     <% @assignments.each do |assignment| %>
       <div class="media">
         <div class="media-body">
           <h4 class="media-heading">
 <!-- #8 <-->   </br>
             <%= link_to assignment.name, assignment %>
           </h4>
           <small>
             <%= assignment.description %>
           </small>
         </div>
       </div>
     <% end %>
   </div>
   <br>
   <p div class="col-md-4">

   </div>

new.html.erb:

<h1>New Assignment</h1>

 <div class="row">
   <div class="col-md-4">
     <p>Guidelines for topics:</p>
     <ul>
       <li>Make sure the topic is appropriate.</li>
       <li>Never insult dogs.</li>
       <li>Smile when you type.</li>
     </ul>
   </div>
   <div class="col-md-8">
     <%= form_for @assignment do |f| %>
       <div class="form-group">
         <%= f.label :name %>
         <%= f.text_field :name, class: 'form-control', placeholder: "Enter assignment name" %>
       </div>
       <div class="form-group">
         <%= f.label :description %>
         <%= f.text_area :description, rows: 8, class: 'form-control', placeholder: "Enter assignment description" %>
       </div>
                <div class="form-group">
      <%= f.label :picture %>
      <%= f.file_field :picture %>
               </div>
      <br />
       <%= f.submit "Save", class: 'button' %>
     <% end %>
   </div>
 </div>

show.html.erb:

<h1><%= @assignment.name %>

 <% if current_user.admin %>
    <%= link_to "Edit Assignment", edit_assignment_path, class: 'btn btn-success' %>
    <%= link_to "Delete Assignment", @assignment, method: :delete, class: 'btn btn-danger', data: { confirm: 'Are you sure you want to delete this assignment?' } %>
<% end %>
 </h1>
 <div class="row">
   <div class="col-md-8">
     <p class="lead"><%= @assignment.description %></p>
 <!-- #10 -->
     <% @assignment.submits.each do |submit| %>
       <div class="media">
         <div class="media-body">
           <h4 class="media-heading">
             <%= link_to submit.name, submit %>
           </h4>
         </div>
       </div>
     <% end %>
   </div>


   <div id="img">
    <%= image_tag @assignment.picture.url %>
  </div>

  </br>
   <div class="col-md-4">
     <%= link_to "Submit Assignment", new_submit_path(@assignment), class: 'button' %>
   </div>
 </div>

edit.html.erb:

<h1>Edit Assignment</h1>

 <div class="row">
   <div class="col-md-4">
     <p>Guidelines for topics:</p>
     <ul>
       <li>Make sure the topic is appropriate.</li>
       <li>Never insult dogs.</li>
       <li>Smile when you type.</li>
     </ul>
   </div>
   <div class="col-md-8">
     <%= form_for @assignment do |f| %>
       <div class="form-group">
         <%= f.label :name %>
         <%= f.text_field :name, class: 'form-control', placeholder: "Enter assignment name" %>
       </div>
       <div class="form-group">
         <%= f.label :description %>
         <%= f.text_area :description, rows: 8, class: 'form-control', placeholder: "Enter assignment description" %>
       </div>
                <div class="form-group">
      <%= f.label :picture %>
      <%= f.file_field :picture %>
               </div>
      <br />
       <%= f.submit "Save", class: 'button' %>
     <% end %>
   </div>
 </div>


schema.rb:

ActiveRecord::Schema.define(version: 20160922102720) do

  create_table "articles", force: :cascade do |t|
    t.string   "title"
    t.text     "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
  end

  create_table "assignments", force: :cascade do |t|
    t.string   "name"
    t.text     "description"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "comments", force: :cascade do |t|
    t.text     "body"
    t.integer  "user_id"
    t.integer  "article_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_index "comments", ["article_id"], name: "index_comments_on_article_id"
  add_index "comments", ["user_id"], name: "index_comments_on_user_id"

  create_table "contacts", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.text     "message"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "submits", force: :cascade do |t|
    t.string   "name"
    t.string   "attachment"
    t.integer  "assignment_id"
    t.integer  "user_id"
    t.datetime "created_at",    null: false
    t.datetime "updated_at",    null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "username",               default: "",    null: false
    t.string   "email",                  default: "",    null: false
    t.string   "encrypted_password",     default: "",    null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,     null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.datetime "created_at",                             null: false
    t.datetime "updated_at",                             null: false
    t.boolean  "admin",                  default: false
    t.string   "firstname"
    t.string   "lastname"
  end

  add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
  add_index "users", ["email"], name: "index_users_on_email", unique: true
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true

end

Rails app removes post images after pushing to heroku

Each time I push the app the images in heroku stop showing up like the link don't exist anoymore

here's my production.rb

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true


  #config.assets.compile = true
  #config.assets.digest = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
  # For large-scale production use, consider using a caching reverse proxy like
  # NGINX, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

  # Asset digests allow you to set far-future HTTP expiration dates on all assets,
  # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # Use the lowest log level to ensure availability of diagnostic information
  # when problems arise.
  config.log_level = :debug

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://ift.tt/rzONfP'

  # Ignore bad email addresses and do not raise email delivery errors.
  # Set this to true and configure the email server for immediate delivery to raise delivery errors.
  # config.action_mailer.raise_delivery_errors = false

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false

  config.serve_static_assets = true
  config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
  config.assets.compile = true
end

and in the gemfile

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

and in the error is

ActionController::RoutingError (No route matches [GET] "/system/posts/images/000/000/003/medium/bfc740afce5d3eeed907cf5d01bded6c.jpg"):

Thanks for the help. Ps. everything else from assets and users are working fine just the post images

After installing Chef Development Kit, i ran "chef verify"

Does anyone know why i am getting this issue.

i dont know the reason i am doing it in ubuntu machine.

Please help me if any had faced the similar kind of issue.

machine config: Ruby 2.2.1 chef 12 server OS Ubuntu

Running verification for component 'berkshelf'
Running verification for component 'test-kitchen'
Running verification for component 'tk-policyfile-provisioner'
Running verification for component 'chef-client'
Running verification for component 'chef-dk'
Running verification for component 'chef-provisioning'
Running verification for component 'knife-spork'
Running verification for component 'delivery-cli'
Running verification for component 'git'
Running verification for component 'opscode-pushy-client'
Running verification for component 'chef-sugar'
..............
Generating cookbook example
- Ensuring correct cookbook file content

================================================================================
Error executing action `create_if_missing` on resource 'template[/tmp/d20160922-20221-1do1qzg/example/spec/unit/recipes/default_spec.rb]'
================================================================================

Chef::Mixin::Template::TemplateError
------------------------------------
undefined method `gsub' for nil:NilClass

Resource Declaration:
---------------------
# In /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/skeletons/code_generator/recipes/cookbook.rb

 84: template "#{cookbook_dir}/spec/unit/recipes/default_spec.rb" do
 85:   source "recipe_spec.rb.erb"
 86:   helpers(ChefDK::Generator::TemplateHelper)
 87:   action :create_if_missing
 88: end
 89: 

Compiled Resource:
------------------
# Declared in /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/skeletons/code_generator/recipes/cookbook.rb:84:in `from_file'

template("/tmp/d20160922-20221-1do1qzg/example/spec/unit/recipes/default_spec.rb") do
  action [:create_if_missing]
  retries 0
  retry_delay 2
  default_guard_interpreter :default
  source "recipe_spec.rb.erb"
  helper_modules [ChefDK::Generator::TemplateHelper]
  declared_type :template
  cookbook_name :code_generator
  recipe_name "cookbook"
  atomic_update true
  path "/tmp/d20160922-20221-1do1qzg/example/spec/unit/recipes/default_spec.rb"
end

Template Context:
-----------------
on line #5
  3: # Spec:: default
  4: #
  5: <%= license_description('#') %>
  6: 
  7: require 'spec_helper'

Platform:
---------
x86_64-linux


ERROR: Chef failed to converge: 

Chef::Mixin::Template::TemplateError (undefined method `gsub' for nil:NilClass) on line #5:

  3: # Spec:: default
  4: #
  5: <%= license_description('#') %>
  6: 
  7: require 'spec_helper'

  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/generator.rb:155:in `license_description'
  (erubis):5:in `block in evaluate'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/erubis-2.7.0/lib/erubis/evaluator.rb:74:in `instance_eval'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/erubis-2.7.0/lib/erubis/evaluator.rb:74:in `evaluate'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/mixin/template.rb:161:in `_render_template'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/mixin/template.rb:147:in `render_template'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/template/content.rb:53:in `file_for_provider'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/file_content_management/content_base.rb:40:in `tempfile'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/file.rb:462:in `tempfile'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/file.rb:339:in `do_generate_content'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/file.rb:150:in `action_create'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider/file.rb:162:in `action_create_if_missing'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/provider.rb:145:in `run_action'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource.rb:603:in `run_action'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:69:in `run_action'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:97:in `block (2 levels) in converge'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:97:in `each'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:97:in `block in converge'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/resource_list.rb:94:in `block in execute_each_resource'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:116:in `call'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:116:in `call_iterator_block'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:85:in `step'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:104:in `iterate'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/stepable_iterator.rb:55:in `each_with_index'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/resource_collection/resource_list.rb:92:in `execute_each_resource'
  /opt/chefdk/embedded/lib/ruby/2.1.0/forwardable.rb:183:in `execute_each_resource'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-12.13.37/lib/chef/runner.rb:96:in `converge'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/chef_runner.rb:43:in `converge'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/command/generator_commands/cookbook.rb:82:in `run'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/command/generate.rb:88:in `run'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/command/base.rb:58:in `run_with_default_options'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/lib/chef-dk/cli.rb:73:in `run'
  /opt/chefdk/embedded/lib/ruby/gems/2.1.0/gems/chef-dk-0.17.17/bin/chef:25:in `<top (required)>'
  /opt/chefdk/bin/chef:74:in `load'
  /opt/chefdk/bin/chef:74:in `<main>'


Caused by: (Chef::Mixin::Template::TemplateError) undefined method `gsub' for nil:NilClass

......................................
---------------------------------------------
Verification of component 'rubocop' succeeded.
Verification of component 'kitchen-vagrant' succeeded.
Verification of component 'openssl' succeeded.
Verification of component 'delivery-cli' succeeded.
Verification of component 'opscode-pushy-client' succeeded.
Verification of component 'berkshelf' succeeded.
Verification of component 'tk-policyfile-provisioner' succeeded.
Verification of component 'fauxhai' succeeded.
Verification of component 'inspec' succeeded.
Verification of component 'chef-sugar' succeeded.
Verification of component 'test-kitchen' succeeded.
Verification of component 'chef-dk' failed.
Verification of component 'chefspec' succeeded.
Verification of component 'knife-spork' succeeded.
Verification of component 'chef-client' succeeded.
Verification of component 'generated-cookbooks-pass-chefspec' succeeded.
Verification of component 'chef-provisioning' succeeded.
Verification of component 'package installation' succeeded.
Verification of component 'git' succeeded.

cache in rails routes

Caching some url for offline, so here one thing is possible to change the protocol from http to https depends on the request url? ie if the request if http://localhost:3000, then the cache thing work with http, and if the request is secure https://localhost:3000 this cache work with https, i think this is not possible but is there any way to do this?

#routes.rb
offline = Rack::Offline.configure do
  cache "http://ift.tt/2cRY3V6"
end

simple_form not saving (but a similar form is)

I am creating an app that has images (actually text) which are shallow nested in posts which are shallow nested in projects. (Please note that my 'images' are actually text, so you can think of them as 'comments')

My routes.rb is:

devise_for :users
resources :projects, shallow: true do
    resources :posts, shallow: true do
        resources :images
    end
end
root 'projects#index'

Which give the following routes:

         post_images GET    /posts/:post_id/images(.:format)          images#index
                     POST   /posts/:post_id/images(.:format)          images#create
      new_post_image GET    /posts/:post_id/images/new(.:format)      images#new
          edit_image GET    /images/:id/edit(.:format)                images#edit
               image GET    /images/:id(.:format)                     images#show
                     PATCH  /images/:id(.:format)                     images#update
                     PUT    /images/:id(.:format)                     images#update
                     DELETE /images/:id(.:format)                     images#destroy
       project_posts GET    /projects/:project_id/posts(.:format)     posts#index
                     POST   /projects/:project_id/posts(.:format)     posts#create
    new_project_post GET    /projects/:project_id/posts/new(.:format) posts#new
           edit_post GET    /posts/:id/edit(.:format)                 posts#edit
                post GET    /posts/:id(.:format)                      posts#show
                     PATCH  /posts/:id(.:format)                      posts#update
                     PUT    /posts/:id(.:format)                      posts#update
                     DELETE /posts/:id(.:format)                      posts#destroy
            projects GET    /projects(.:format)                       projects#index
                     POST   /projects(.:format)                       projects#create
         new_project GET    /projects/new(.:format)                   projects#new
        edit_project GET    /projects/:id/edit(.:format)              projects#edit
             project GET    /projects/:id(.:format)                   projects#show
                     PATCH  /projects/:id(.:format)                   projects#update
                     PUT    /projects/:id(.:format)                   projects#update
                     DELETE /projects/:id(.:format)                   projects#destroy
                root GET    /                                         projects#index

My models are as follows:

project.rb

class Project < ApplicationRecord
    belongs_to :user
    has_many :posts
    has_many :images
end

post.rb

class Post < ApplicationRecord
  belongs_to :project
  belongs_to :user
  has_many :images
end

image.rb

class Image < ApplicationRecord
  belongs_to :project
  belongs_to :post
  belongs_to :user
end

My post table migration is:

create_table :posts do |t|
  t.string :title
  t.text :content
  t.references :project, foreign_key: true
  t.references :user, foreign_key: true

  t.timestamps
end

And image table migration is:

create_table :images do |t|
  t.text :caption
  t.references :project, foreign_key: true
  t.references :post, foreign_key: true
  t.references :user, foreign_key: true

  t.timestamps
end

I am using a simple_form to create posts for my projects, which is working perfectly. The controller and view for creating posts are:

def create
    @project = Project.find(params[:project_id])
    @post = @project.posts.create(post_params)
    @post.user_id = current_user.id

    if @post.save
        redirect_to post_path(@post)
    else
        render 'new'
    end
end
-------------------------------------------------------
private
    def post_params
        params.require(:post).permit(:title, :content)
    end
end
-------------------------------------------------------
<%= simple_form_for([@project, @project.posts.build]) do |f| %>
    <%= f.input :title, label: "Post Title" %>
    <%= f.input :content, label: "Post Descriptioon" %>
    <%= f.button :submit %>
<% end %>

This works great. I want to do the exact same thing, now with images for a post. Looking at my routes, I would have thought that the relationship of post to project is basically the same as image to post. So I have used a similar code as below:

def create
    @post = Post.find(params[:post_id])
    @image = @post.images.create(image_params)
    @image.user_id = current_user.id

    if @image.save
        flash[:alert] = "Image saved successfully!"
        redirect_to post_path(@post)
    else
        flash[:alert] = "Image not saved!"
        render 'new'
    end
end
-------------------------------------------------------
private
    def image_params
    params.require(:image).permit(:caption)
    end
end
-------------------------------------------------------
<%= simple_form_for([@post, @post.images.build]) do |f| %>
    <%= f.input :caption %>
    <%= f.button :submit %>
<% end %>

When clicking submit, nothing is saved and a new form is rendered. I have added an alert to check that in fact it is not saving and the alert is working and telling me that it has not saved. Why would it not be saving?

Please remember that for this my 'images' are actually text (in the way a comment would be). Sorry if this is confusing.

Any help with this would be appreciated. Thanks!

Why is find_in_batches running again after completion in Rails 3.2, ruby 1.9.3?

How to do I mass update using find_in_batches when there are around 1 million records where it should take a condition and update those records alone.

# For testing in my local, here are the DB stats,
# Total no of users => 2000,
# Total no of users with name field having nil value => 1,
# Total no of users with name field present => 1999,
# Objective=> Use find_in_batches to run a batch generation of name field for all users who do not have name field.
# Expected Result => Should generate name field for that 1 record and exit from batch_update code
# Obtained Result => Its updating that 1 user's name and then again its running for all 2000 users.

In production this could lot of trouble as I have million records.

I have tried this out:

 task :add_name_to_all_users => :environment do
   i=0
   puts "started at :#{Time.now}|Batch Size: 12"
   Name.where("name is null").find_in_batches(batch_size: 12) do |names|
     sleep(2)
     names.each {|n| n.save!; i+=1;} 
     puts "updated #{i} records at: #{Time.now}"
   end
   puts "Completed the Task at: #{Time.now}"
 end

This is what I get in console,

started at :2016-09-22 10:33:18 +0530|Batch Size: 12
updated 1 records at: 2016-09-22 10:33:21 +0530
Completed the Task at: 2016-09-22 10:33:21 +0530
started at :2016-09-22 10:33:21 +0530|Batch Size: 12
updated 12 records at: 2016-09-22 10:33:27 +0530
updated 24 records at: 2016-09-22 10:33:33 +0530

My concern: Why is it starting again after this line:

Completed the Task at: 2016-09-22 10:33:21 +0530

The above code works but it keeps running till it has looped through all the records. The where method is not working for me. And the loop is starting again after updating that one record which had name as nil.

mercredi 21 septembre 2016

Issue with rails saying a nested model's field is blank when it is not

I'm having an issue with getting a nested model to save properly when it has validations. This seems to only be happening to a single field in this model.

I have two models, a Veterinarian

class Veterinarian < ApplicationRecord
  has_many :licenses
  accepts_nested_attributes_for :licenses, allow_destroy: true, reject_if: :all_blank
end

and a License

class License < ApplicationRecord
  belongs_to :veterinarian
  validates :number, :expiration_date, presence: true
end

My controller action is doing nothing but calling Veterinarian.create(vet_params) with vet_params looking like this rendered out as JSON.

{  
  "zip_code":"",
  "title":"",
  "bio":"",
  "photo":"",
  "licenses_attributes":{  
    "0":{  
      "number":"6436436446",
      "expiration_date":"09/06/2018",
      "_destroy":"false"
    },
    "1":{  
      "number":"Test Number",
      "expiration_date":"09/16/2020",
      "_destroy":"false"
    },
    "2":{  
      "number":"test 2",
      "expiration_date":"09/30/2016",
      "_destroy":"false"
    }
  }
}

The proper params are being sent to 'create()' however with the nested licenses it keeps throwing an error saying expiration_date cannot be blank. This is ONLY happening for additional licenses past the first one. The first one validates just fine.

I am at a loss as to what would be causing this. I've never seen this happen before. Any ideas would be greatly appreciated.

This is Rails 5 btw.

Rails Not able to save data, association

I'm doing a parking permit website. The problem I met is that I'm not able to save my data to the PERMIT database which associated with the USER database. The problem i think is I didn't bring the user to the permit(Maybe i missed something). I found out the error when I trying to save from Permit.errors.full_messages is ["User must exist"]. Any help is appreciated, Thank you!

Schema.rb

ActiveRecord::Schema.define(version: 20160920143651) do

  create_table "permits", force: :cascade do |t|
    t.string   "vehicle_type"
    t.string   "name"
    t.string   "studentid"
    t.string   "department"
    t.string   "carplate"
    t.string   "duration"
    t.date     "permitstart"
    t.date     "permitend"
    t.integer  "user_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.index ["user_id"], name: "index_permits_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "password_digest"
    t.integer  "user_type"
  end

end

Create_permit.rb

class CreatePermits < ActiveRecord::Migration[5.0]
  def change
    create_table :permits do |t|
      t.string :vehicle_type
      t.string :name
      t.string :studentid
      t.string :department
      t.string :carplate
      t.string :duration
      t.date :permitstart
      t.date :permitend
      t.references :user, foreign_key: true

      t.timestamps
    end
    add_index :permits, :user_id
  end
end

Permit_controller

class PermitsController < ApplicationController
  before_action :set_permit, only: [:show, :destroy]
  def index
    @permits = Permit.all
  end

  def new
    @permits = Permit.new
  end

  def create
    @permits = Permit.new(permit_params)

      if @permits.save
        redirect_to @permits
      else
        redirect_to contact_path
      end

  end

  def destroy
    Permit.destroy_all(user_id: 1)
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'Permit was successfully canceled.' }
      format.json { head :no_content }
    end
  end

  def show
    @permits = Permit.find(params[:id])
  end

  def update
    respond_to do |format|
      if @permits.update(user_params)
        format.html { redirect_to @user, notice: 'Permit was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

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

  # Never trust parameters from the scary internet, only allow the white list through.
  def permit_params
    params.require(:permit).permit(:vehicle_type, :name, :studentid, :department, :carplate, :duration, :permitstart, :permitend)
  end
end

user.rb

class User < ApplicationRecord
  has_many :permits
  has_secure_password
end

Permit.rb

    class Permit < ApplicationRecord
    belongs_to :user
    end

permit/new.html.erb
<% provide(:title, 'New Permit') %>
<h1>Permit Application</h1>

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

        <%= f.label :"Vehicle" %>
        <%= f.text_field :vehicle_type, class: 'form-control' %>

        <%= f.label :"License Plate" %>
        <%= f.text_field :carplate, class: 'form-control' %>

        <%= f.label :"Student ID" %>
        <%= f.text_field :studentid, class: 'form-control' %>

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

        <%= f.label :"Department of applicant" %>
        <%= f.text_field :department, class: 'form-control' %>

        <%= f.label :permit_start %>
        <%= f.date_select :permitstart, class: 'form-control' %>

        <%= f.label :permit_end %>
        <%= f.date_select :permitend,  class: 'form-control'  %>


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

How can I authenticate a user with admin attribute for rails_admin with devise

I am fairly new to ruby on rails. I habe set up a mysql database, connected it with a rails app, installed the devise gem and rails_admin gem. So far so good, everything works as it should. Now I also added a usergroup attribute to the users table, to identify different user group. Only "admin" should be allowed to access rails admin. I already use the predefined commands in /app/config/initializers/rails_admin.rb

   RailsAdmin.config do |config|

  ### Popular gems integration

  ## == Devise ==
   config.authenticate_with do
     warden.authenticate! scope: :admin
   end
   config.current_user_method(&:current_user)

  ## == Cancan ==
  # config.authorize_with :cancan

  ## == Pundit ==
  # config.authorize_with :pundit

  ## == PaperTrail ==
  # config.audit_with :paper_trail, 'User', 'PaperTrail::Version' # PaperTrail >= 3.0.0

  ### More at http://ift.tt/1zzoq7G

  ## == Gravatar integration ==
  ## To disable Gravatar integration in Navigation Bar set to false
  # config.show_gravatar true

  config.actions do
    dashboard                     # mandatory
    index                         # mandatory
    new
    export
    bulk_delete
    show
    edit
    delete
    show_in_app

    ## With an audit adapter, you can add:
    # history_index
    # history_show
  end
end

This works so far that you have to login before you can access the page. Now there also has to be a check wether current_user.usergroup = 'admin'.

In devise this is also explained as one possible method to 'handle' usergroups. http://ift.tt/1klqdGy

But I am pretty confused how to insert this check into the config that way.

How to make a pre-emptive basic authentication call using savon client in ruby?

I am doing the following code in savon but unable to do as it requires pre-emptive authorization. I have verified in soapUI but unable to run in savon. Could somebody help?

client = Savon.client(ssl_verify_mode: :none) do
  wsdl '/Users/sp/jda_notifications/TransportationManagerService.wsdl'
  endpoint 'http://localhost:8088/webservices/services/TransportationManager'
  basic_auth('VENTURE', 'VENTURE')
end

downloading ppt format in rails using powerpoint ruby gem

1st Part: I Have implemented powerpoint gem in rails 3.2 and ruby 1.9.2

I am just trying to download a html.erb file in pptx format

My codes like this:

@filters = generate_filters_for_manual_report(params)

@deck = Powerpoint::Presentation.new

title = 'Bicycle Of the Mind'

subtitle = 'created by Steve Jobs'

@deck.add_intro title, subtitle

@deck.save('/home/sahil/test6.pptx')

send_data @deck, :filename => '/home/sahil/test6.pptx', :disposition => 'inline', :type => "multipart/related"

it is getting saved in local directory as a pptx file. but unbable to downlaod as as pptx file.

Part2

the above is for text how Can i implement so that html.erb file for customer details and customer image will be show in pptx slider.

Any help will be greatly appreciated. thanks

Can't save my data into sqlite database

I trying to implement a Parking Permit application page using ROR. I couldn't get my data save into the database which the permit database is associated with the user. The program won't save the data and execute the else statement. There is no error generated, i think i have missed something but i don't know the exact problem. Any helps are appreciated!

Permit_controller.rb

class PermitsController < ApplicationController
  before_action :set_permit, only: [:show, :destroy]
  def index
    @permits = Permit.all
  end

  def new
    @permits = Permit.new
  end

  def create
    @permits = Permit.new(permit_params)
    if @permits.save
      redirect_to root_path
    else
      redirect_to contact_path
    end
  end

  def destroy
  end

  def show
    @permits = Permit.find(params[:id])
  end
  private
  # Use callbacks to share common setup or constraints between actions.
  def set_permit
    @permits = Permit.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def permit_params
    params.require(:permit).permit(:vehicle_type, :name, :studentid, :department, :carplate,:permitstart, :permitend)
  end
end

Permit.rb

class Permit < ApplicationRecord
  belongs_to :user
end

Create_permit.rb

class CreatePermits < ActiveRecord::Migration[5.0]
  def change
    create_table :permits do |t|
      t.string :vehicle_type
      t.string :name
      t.string :studentid
      t.string :department
      t.string :carplate
      t.date :permitstart
      t.date :permitend
      t.references :user, foreign_key: true

      t.timestamps
    end
    add_foreign_key :permits, :user
    add_index :permits, [:user_id, :created_at]
  end
end

User.rb

    class User < ApplicationRecord
      has_secure_password
      has_many :permits
    end

    #book pg 264 Validation

permit/new.html.erb
<% provide(:title, 'New Permit') %>
<h1>Permit Application</h1>

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

        <%= f.label :"Vehicle" %>
        <%= f.text_field :vehicle_type, class: 'form-control' %>

        <%= f.label :"License Plate" %>
        <%= f.text_field :carplate, class: 'form-control' %>

        <%= f.label :"Student ID" %>
        <%= f.text_field :studentid, class: 'form-control' %>

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

        <%= f.label :"Department of applicant" %>
        <%= f.text_field :department, class: 'form-control' %>

        <%= f.label :permit_start %>
        <%= f.date_select :permitstart, class: 'form-control' %>

        <%= f.label :permit_end %>
        <%= f.date_select :permitend,  class: 'form-control'  %>


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

schema.rb

ActiveRecord::Schema.define(version: 20160921071908) do


  create_table "permits", force: :cascade do |t|
    t.string   "vehicle_type"
    t.string   "name"
    t.string   "studentid"
    t.string   "department"
    t.string   "carplate"
    t.date     "permitstart"
    t.date     "permitend"
    t.integer  "user_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
    t.index ["user_id"], name: "index_permits_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "password_digest"
    t.integer  "user_type"
  end

end

Moving CKeditor images from instance local to S3 URL's getting changed and access issues?

In my Rails app I was using ckeditor with Carrierwave with storage set as :file. Because of this setup whenever a user used to upload an image from CKEditor it would save in instance /public/system/ckeditor and then I had an command to sync it to S3 so that other instances could access the same image.

So whenever I would render the images in the view page, the image path for all images would point to that particular instance's location(/public/system/ckeditor), which would access the image from S3 in turn because S3 was mounted, and there was no need to authenticate separately or have an expiry URL. The images were stored in S3 as private.

It was working fine except few times when s3 used to get unmounted, I had to remount it.

Now I want to remove this process of storing the image in local instance and then syncing it. So I have made following changes to s3.rb:

CarrierWave.configure do |config|
  config.fog_credentials = {
      :provider               => 'AWS',
      :aws_access_key_id      => "klajhdfaljkdjklasd",
      :aws_secret_access_key  => "alksdjklajdlkajsxxxxxxxxx",
      :region                 => 'us-east-1'
  }
  config.fog_public     = false  
  config.fog_directory  = "s3-bucket"
end

Now the images are directly uploaded as private, but while reading the images I get 403 Forbidden in browser console.

There is one more problem in CKEditor images migration, the URL is hardcoded in the database, how can I change it as there are over 1 million records.

Similarly I have paperclip which was storing images in local which was being synced to s3, and then the images were accessed via instance through S3. But now I get 403 same as that of CKEditor.

PAPERCLIP_STORAGE_OPTIONS = {
   :styles => { :thumb25 => "25x25>", :thumb50 => "50x50>", :thumb250 => "250x250>"  },
   :url => "/system/:class/:id",
   :storage => :s3,
    :bucket => 's3-bucket',
    :s3_credentials => {:access_key_id => "ajkhdasjhdjkanhsdjknasd", :secret_access_key => "adasdasdasd+aadasd"},
    :s3_protocol => :https,
    :s3_permissions => :private,
}

Now I have too many models having code for displaying images, If I have to add authenticate object code, that would require lot of rework both in paperclip and CKEditor case.

Please let me know If there is any more clarification needed.