samedi 31 décembre 2016

Ruby on rails , test is saying a column doesn't exist but its on the schema

in my clients table, I have a column named email. But when I made the tests for the clients controller and the model, the tests kept on saying that the clients table has no column named email.

although I do admit that I didn't initially put that column when I created my table, but I added the column via a separate migration. I ran rake db:migrate and even tried rake db:drop:all, rake db:create:all and then rake db:migrate and it still didn't change anything.

the email column was also added as an index for the clients table.

this is my schema:

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

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

  add_index "clients", ["email"], name: "index_clients_on_email", unique: true

  create_table "projects", force: :cascade do |t|
    t.text     "project_description", null: false
    t.string   "project_timescale"
    t.datetime "created_at",          null: false
    t.datetime "updated_at",          null: false
    t.integer  "client_id"
  end

  add_index "projects", ["client_id"], name: "index_projects_on_client_id"

end

the initial migration for the clients table:

class CreateClients < ActiveRecord::Migration
  def change
    create_table :clients do |t|
      t.string :name, presence: true, null: false
      t.timestamps null: false
    end
  end
end

migration to add email as an index for the client table:

class AddIndexToClient < ActiveRecord::Migration
  def change
    add_index:clients, :email, unique: true
  end
end

migration to add the email column:

class AddEmailToClient < ActiveRecord::Migration
  def change
    add_column :clients, :email, :text
  end
end

vendredi 30 décembre 2016

Problems displaying a list of my model instances

in the application I have made, I have clients and projects. a Client has many projects and a project belongs to a client. Projects are made by first creating a client, and each project object is created via a client.

After I create a project object and I hit save, i get this error:

NoMethodError in ProjectsController#show

undefined method `set_project' for # Did you mean? edit_project_url

the following is my project controller:

class ProjectsController < ApplicationController
  before_action :set_project, only: [:show, :edit, :update, :destroy]
  before_action :set_client, only: [:new, :create] 

  # GET /projects
  # GET /projects.json
  def index
    @projects = Project.all
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
  end

  # GET /projects/new
  def new
    @project = @client.projects.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    #@project = Project.new(project_params)
    @project = @client.projects.new(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_client
      #@project = Project.find(params[:id])

      @client = Client.find_by(id: params[:client_id]) || Client.find(project_params[:client_id]) 
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:client_id, :project_description, :project_timescale)
    end
end

This is my client controller:

class ClientsController < ApplicationController
  before_action :set_client, only: [:show, :edit, :update, :destroy]

  # GET /clients
  # GET /clients.json
  def index
    @clients = Client.all
  end

  # GET /clients/1
  # GET /clients/1.json
  def show
  end

  # GET /clients/new
  def new
    @client = Client.new
  end

  # GET /clients/1/edit
  def edit
  end

  # POST /clients
  # POST /clients.json
  def create
    @client = Client.new(client_params)

    respond_to do |format|
      if @client.save
        format.html { redirect_to @client, notice: 'Client was successfully created.' }
        format.json { render :show, status: :created, location: @client }
      else
        format.html { render :new }
        format.json { render json: @client.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /clients/1
  # PATCH/PUT /clients/1.json
  def update
    respond_to do |format|
      if @client.update(client_params)
        format.html { redirect_to @client, notice: 'Client was successfully updated.' }
        format.json { render :show, status: :ok, location: @client }
      else
        format.html { render :edit }
        format.json { render json: @client.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /clients/1
  # DELETE /clients/1.json
  def destroy
    @client.destroy
    respond_to do |format|
      format.html { redirect_to clients_url, notice: 'Client was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def client_params
      params.require(:client).permit(:name, :email)
    end
end

the following are the view assosciated with the project model:

the form:

<%= form_for @project do |f| %>
  <% if @project.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= "#{pluralize(@project.errors.count, "error")} prohibited this project from being saved:" %>
      </h2>
      <ul>
        <% @project.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.hidden_field :client_id, value: @project.client.id  %>
  <div class="field">
    <%= f.label :client %>
      <p>
        <%= @project.client.name %>
      </p>
  </div>
  <div class="field">
    <%= f.label :project_description %>
    <%= f.text_area :project_description %>
  </div>
  <div class="field">
    <%= f.label :project_timescale %>
    <%= f.text_field :project_timescale %>
  </div>
  <div class="actions">
    <%= f.submit 'Save' %>
  </div>
<% end %>

Edit:

%h1 Editing project

= render 'project_form'

= link_to 'Show', @project
\|
= link_to 'Back', projects_path

Index:

%h1 Listing projects

%table
  %thead
    %tr
      %th Client
      %th Project description
      %th Project timescale
      %th
      %th
      %th

  %tbody
    - @projects.each do |project|
      %tr
        %td= project.client.name
        %td= project.project_description
        %td= project.project_timescale
        %td= link_to 'Show', project
        %td= link_to 'Edit', edit_project_path(project)
        %td= link_to 'Destroy', project, :method => :delete, :data => { :confirm => 'Are you sure?' }

%br

= link_to 'New Project', new_project_path

New:

%h1 New project

= render 'project_form'

= link_to 'Back', projects_path

Show:

%p#notice= notice

%p
  %b Client:
  = @project.client.name
%p
  %b Project description:
  = @project.project_description
%p
  %b Project timescale:
  = @project.project_timescale

= link_to 'Edit', edit_project_path(@project)
\|
= link_to 'Back', projects_path

Unit testing a polymorphic association with fixtures in rails 4

I need to unit test a promotions model where every campaign has a URL. There is a polymorphic association between promotions and reference_link. the reference link fixture reference_link: linkable: fix_1 (PromoCode)

How do I convince rails that the promotions fixture does indeed have a URL belonging to it?

In promotions test helper

test "should have a URL associated with the promo code" do
promo_code = promo_codes(:fix_1)
promo_code.reference_link.url = nil
assert_not promo_code.valid?
promo_code2 = promo_codes(:fix_2)
assert promo_code2.valid?

end

promocode.rb

class PromoCode < ActiveRecord::Base

belongs_to :reward
has_one :reference_link, as: :linkable, dependent: :destroy

validates :email, presence: true
validates :code, presence: true

end

reference_link.rb

class ReferenceLink < ActiveRecord::Base belongs_to :linkable, polymorphic: true,touch: true

 validates :link_name, presence: true
 validates :link_url, presence: true 

 validates_format_of :link_url, :with => /\A#{URI::regexp(['http',    'https'])}\z/

validates_length_of :link_url,:link_name, :maximum => 255  

end

Rails: Search by custom instance method's value using tire gem & elasticsearch

For example, I have Article model like

class Article < ActiveRecord::Base
  #Columns: id, title, status_number...etc

  STATUSES = {1 => "SUCCESS", 2 => "REJECTED"}

  include Tire::Model::Search
  include Tire::Model::Callbacks

  def display_status
    STATUSES[status_number]
  end

  def self.search(params)
    tire.search(load: true, page: params[:page], per_page: 2) do
      query do
        boolean do
          must { string params[:query], default_operator: "AND" } if params[:query].present?
        end
    end
  end
end

how to include display_status as "SUCCESS" by default in search method? I tried

query do
  boolean do
    must { string params[:query], default_operator: "AND" } if params[:query].present?
    must { term :display_status , "SUCCESS" } 
  end
end

But couldn't get result. Please help to solve this problem. Thanks

What i wrong with my html.erb file?

from the code below, I get the following error:

/home/ubuntu/workspace/portfolio/app/views/projects/_project_form.html.erb:36: syntax error, unexpected keyword_ensure, expecting end-of-input

because it is a syntax error, I am guessing I wont need to provide other details but if you guys need me to post more feel free to ask.

    <%= form_for @project do |f| %>
  <% if @project.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= "#{pluralize(@project.errors.count, "error")} prohibited this project from being saved:" %>
      </h2>
      <ul>
        <% @project.errors.full_messages.each do |msg| %>
          <li>
            <%= msg %>
          </li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :client %>
      <p>
        <%= @project.client.name %>
      </p>
      <%= f.hidden_field:note_id, value: @project.client.id  %>
    <% end %>
  </div>
  <div class="field">
    <%= f.label :project_description %>
    <%= f.text_area :project_description %>
  </div>
  <div class="field">
    <%= f.label :project_timescale %>
    <%= f.text_field :project_timescale %>
  </div>
  <div class="actions">
    <%= f.submit 'Save' %>
  </div>
  <% end %>

order with recent created record in multiple associated models rails

i have three associated models

artical.rb:

 has_many :texts
 has_many :notes
 has_many :attachments

i want to order artical with recent created record

artical 6 = text: 20 dec , note: 19 dec, attachment: 20dec
artical 9 = text: 18 dec , note: 21 dec, attachment: not present 
artical 10 = text: not present , note: 30 dec, attachment: not present

Order will Be:

 ###artical Index Page 

 artical 10
 artical 9 
 artical 6

Thanks In Advance

jeudi 29 décembre 2016

Dynamically generate link_to for different models using common partial - Rails 4

i want to use a common partial to render a listing page and its going good expect i am facing a problem to generate dynamic link_to for :edit and :delete action which is common.

so i have @menu and @picture model in two different views rendering the same common partial (which i created).

this is my common partial.

shared/_index_common_grid.html.erb

               <% pictures.each do |picture| %>
                  <div class="col-sm-4 pull-left">
                      <div class="thumbnail">
                          <div class="caption"> 
                               <h4><%= picture.title.capitalize%></h4>
                              <p class="text-muted">
                              <!--THIS IS WHERE I WANT TO HANDLE DYNAMIC GENERATION OF LINK_TO FOR @picture and @menu models --> 
                                 <%= link_to "Edit", [:edit, current_user,@request,@shop,picture]%>
                              |  <%= link_to "Delete", [current_user,@request,@shop,picture],:data=>{:confirm=>"Are you sure ?"}%>
                              | <span class="pull-right"><%= show_formatted_date(picture.created_at)%></span>                                
                              </p>
                          </div>
                      </div>
                  </div> 
                <%end%>

this is my one view using above common partial,there is one more similar to this except i pass different model.

##my view page --------pictures/index
                  <%unless @pictures.blank?%>   
                      <%= render partial: "shared/index_common_grid", locals: {pictures: @pictures}%>
                  <%end%>

I dont want to go with switch case in application_helper which can be done easily.

Model's attributes are being failed validation when they are not passed

is it logical that when I don't pass attributes' values, they failed the validation of the custom validation method, even though I am not trying to update them, however, the value is valid, and it was created successfully at the first place.

   Parameters: {"utf8"=>"✓", "id"=>"2", "shop"=>{"allowed_users"=>"5"}, "commit"=>"עדכן"}

The validation fails only for the custom validation method, for :shop_customer_id.

Define article owner ( Couldn't find Article without an ID)

I'm trying to define an article owner, for that I have to independent resources, which are not nested in each other (user, article).

Each article has an user_id attribute which corresponds to the id of the user who created the article.

Now I'm trying to match both so I can create an article owner.

This is how I'm trying to do it:

Articles_controller.rb

def show
      @article = Article.find(params[:id])
      @user_id = Article.find(params[:user_id])
      @user= User.find_by(id: user_id)
end

Capistrano assets:precompile , undefined $modal-delay for css

Following is my deploy.rb

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

set :linked_dirs,  %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system}

namespace :puma do
  desc 'Create Directories for Puma Pids and Socket'
  task :make_dirs do
    on roles(:app) do
      execute "mkdir #{shared_path}/tmp/sockets -p"
      execute "mkdir #{shared_path}/tmp/pids -p"
    end
  end

  before :start, :make_dirs
end



namespace :deploy do
  desc "Make sure local git is in sync with remote."
  task :check_revision do
    on roles(:app) do
      unless `git rev-parse HEAD` == `git rev-parse origin/master`
        puts "WARNING: HEAD is not the same as origin/master"
        puts "Run `git push` to sync changes."
        exit
      end
    end
  end

  desc 'generate sitemaps'
  task :generatesitemap do
    on roles(:app) do
      execute "cd #{release_path}"
      execute "ruby sitemap.rb"
    end
  end

  desc 'Initial Deploy'
  task :initial do
    on roles(:app) do
      before 'puma:start'
      invoke 'deploy'
    end
  end

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      # invoke 'puma:restart'
      Rake::Task['puma:restart'].reenable
    end
  end

  before :starting,     :check_revision
  after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :generatesitemap
  after  :finishing,    :restart
end

# ps aux | grep puma    # Get puma pid
# kill -s SIGUSR2 pid   # Restart puma
# kill -s SIGTERM pid   # Stop puma

Following is my capfile

# Load DSL and set up stages
require "capistrano/setup"

# Include default deployment tasks
require "capistrano/deploy"

require 'capistrano/rails'
require 'capistrano/bower'
require 'capistrano/bundler'
require 'capistrano/rvm'
require 'capistrano/puma'
require 'capistrano/puma/nginx'
# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob("lib/capistrano/tasks/*.rake").each { |r| import r }

When I deploy to staging environment. I am constantly getting this error "Sass::SyntaxError: Undefined variable: "$modal-delay"

I have searched through my stylesheets and I don't have this variable $modal-delay used anywhere in my stylesheets. I also tried defining this variable in application.scss. but still this error keeps coming.

I have also cleaned, clobbed my assets, i have also cleared my tmp/cache folder.

Following is my application.scss file

$modal-delay : 3;


 @import "animate.scss";
 @import "bootstrap.scss";
 @import "font-awesome.scss";
 @import "material-design-iconic-font.scss";
 @import "reset.scss";
 @import "responsive-menu.scss";
 @import "owl.carousel.scss";
 @import "easy-responsive-tabs.scss";
 @import "mediaelementplayer.scss";
 @import "style1.scss";
 @import "responsive.scss";
 @import "custom.scss";
 @import "messenger/build/css/messenger.css";
 @import "messenger/build/css/messenger-theme-future.css";
 @import "bootstrap-suggest.scss";

I am looking at this thread http://ift.tt/2iaTt6u

Thanks

mercredi 28 décembre 2016

Determine if a serialized hash has changed in active record.

What would the best way to determine if a hash has changed, normally there's changes, and changed method but it's hard to pinpoint if you are only concerned for the hash changes.

For example

class Person
   attr_accessible : name

   serialize :actions, Hash
end

with this, the hash actions can do many things such as actions[:eat], actions[:work][:something_else]

The problem with this is that for a specific use case, I'm only concerned for the actions if it has changed, so the methods changes, and changed can't be that reliable.

ActionController::Metal How to catch all exceptions to send notification email?

I am using ActionController::Metal inherted controllers for for rails services, I want to catch all exceptions , So that I can notify myself through email

rescue_from Exception is not working

I have used above code in another app in application controller it is working good But not in this case

Which module should be included in to base controller in order to use it any help?

BSON::InvalidObjectId illegal ObjectId format Rails 3.1.1

I'm getting the following error when trying to use the delete method in a Ruby on Rails application.

BSON::InvalidObjectId in ServicesController#destroy

I'm using Rails 3.1.1 and MongoDB v2.4.15

Below is the Delete link in question.

%li= link_to 'Delete', @service, :method => :delete, :confirm => "Are you sure you want to delete this service?"

Here is the log error:

Started DELETE "/services/appeals" for 127.0.0.1 at 2016-12-21 11:08:42 -0500
Creating scope :orderable_scope. Overwriting existing method Service.orderable_scope.
  Processing by ServicesController#destroy as HTML
  Parameters: {"authenticity_token"=>"xxx", "id"=>"appeals"}
Completed 500 Internal Server Error in 11ms

BSON::InvalidObjectId (illegal ObjectId format: appeals):

When deleting items in other collections it works fine. I'm able to use the "services" edit link without errors. Below is the working Delete link and logs for deleting an attorney.

Working Link %li= link_to "Delete", @attorney, :method => :delete, :confirm => "Are you sure you want to delete this attorney?"

Working Log

Started DELETE "/attorneys/first-last" for 127.0.0.1 at 2016-12-21 10:37:07 -0500
Creating scope :orderable_scope. Overwriting existing method Attorney.orderable_scope.Processing by AttorneysController#destroy as HTMLParameters: {"authenticity_token"=>"xxx", "id"=>"first-last"}
MONGODB x_development['system.namespaces'].find({})
MONGODB x_development['attorneys'].find({:slug=>"first-last"}).limit(-1).sort([[:_id, :asc]])
MONGODB x_development['system.namespaces'].find({})
MONGODB x_development['users'].find({:_id=>BSON::ObjectId('585a9dbc737da97cbd000006')}).limit(-1).sort([[:_id, :asc]])
Creating scope :orderable_scope. Overwriting existing method Service.orderable_scope.
MONGODB x_development['system.namespaces'].find({})
Redirected to http://ift.tt/2hHOsSB
Completed 302 Found in 69ms` 

It's another developers application that I'm trying to get working correctly again. I'm not very experienced with Ruby, Rails, or MongoDB.

UPDATE Below is the Full Trace

bson (1.4.0) lib/bson/types/object_id.rb:126:in `from_string'
mongoid (2.4.12) lib/mongoid/fields/internal/object_id.rb:38:in `serialize'
mongoid (2.4.12) lib/mongoid/criterion/optional.rb:97:in `for_ids'
mongoid (2.4.12) lib/mongoid/criteria.rb:310:in `search'
mongoid (2.4.12) lib/mongoid/criterion/inclusion.rb:125:in `find'
mongoid (2.4.12) lib/mongoid/finders.rb:84:in `find'
inherited_resources (1.3.1) lib/inherited_resources/base_helpers.rb:44:in `resource'
cancan (1.6.7) lib/cancan/inherited_resource.rb:11:in `load_resource_instance'
cancan (1.6.7) lib/cancan/controller_resource.rb:32:in `load_resource'
cancan (1.6.7) lib/cancan/controller_resource.rb:25:in `load_and_authorize_resource'
cancan (1.6.7) lib/cancan/controller_resource.rb:10:in `block in add_before_filter'
activesupport (3.1.1) lib/active_support/callbacks.rb:439:in `_run__3707406960644643515__process_action__1333295842175195574__callbacks'
activesupport (3.1.1) lib/active_support/callbacks.rb:386:in `_run_process_action_callbacks'
activesupport (3.1.1) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.1.1) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.1.1) lib/action_controller/metal/rescue.rb:17:in `process_action'
actionpack (3.1.1) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action'
activesupport (3.1.1) lib/active_support/notifications.rb:53:in `block in instrument'
activesupport (3.1.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.1.1) lib/active_support/notifications.rb:53:in `instrument'
actionpack (3.1.1) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.1.1) lib/action_controller/metal/params_wrapper.rb:201:in `process_action'
actionpack (3.1.1) lib/abstract_controller/base.rb:121:in `process'
actionpack (3.1.1) lib/abstract_controller/rendering.rb:45:in `process'
actionpack (3.1.1) lib/action_controller/metal.rb:193:in `dispatch'
actionpack (3.1.1) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.1.1) lib/action_controller/metal.rb:236:in `block in action'
actionpack (3.1.1) lib/action_dispatch/routing/route_set.rb:65:in `call'
actionpack (3.1.1) lib/action_dispatch/routing/route_set.rb:65:in `dispatch'
actionpack (3.1.1) lib/action_dispatch/routing/route_set.rb:29:in `call'
rack-mount (0.8.3) lib/rack/mount/route_set.rb:152:in `block in call'
rack-mount (0.8.3) lib/rack/mount/code_generation.rb:96:in `block in recognize'
rack-mount (0.8.3) lib/rack/mount/code_generation.rb:131:in `optimized_each'
rack-mount (0.8.3) lib/rack/mount/code_generation.rb:95:in `recognize'
rack-mount (0.8.3) lib/rack/mount/route_set.rb:141:in `call'
actionpack (3.1.1) lib/action_dispatch/routing/route_set.rb:532:in `call'
mongoid (2.4.12) lib/rack/mongoid/middleware/identity_map.rb:33:in `block in call'
mongoid (2.4.12) lib/mongoid.rb:133:in `unit_of_work'
mongoid (2.4.12) lib/rack/mongoid/middleware/identity_map.rb:33:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
rack (1.3.6) lib/rack/etag.rb:23:in `call'
rack (1.3.6) lib/rack/conditionalget.rb:35:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/head.rb:14:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/flash.rb:243:in `call'
rack (1.3.6) lib/rack/session/abstract/id.rb:195:in `context'
rack (1.3.6) lib/rack/session/abstract/id.rb:190:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/cookies.rb:331:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (3.1.1) lib/active_support/callbacks.rb:392:in `_run_call_callbacks'
activesupport (3.1.1) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.1.1) lib/action_dispatch/middleware/callbacks.rb:28:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/reloader.rb:68:in `call'
rack (1.3.6) lib/rack/sendfile.rb:101:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
railties (3.1.1) lib/rails/rack/logger.rb:13:in `call'
rack (1.3.6) lib/rack/methodoverride.rb:24:in `call'
rack (1.3.6) lib/rack/runtime.rb:17:in `call'
activesupport (3.1.1) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.3.6) lib/rack/lock.rb:15:in `call'
actionpack (3.1.1) lib/action_dispatch/middleware/static.rb:53:in `call'
railties (3.1.1) lib/rails/engine.rb:456:in `call'
railties (3.1.1) lib/rails/rack/content_length.rb:16:in `call'
railties (3.1.1) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.3.6) lib/rack/handler/webrick.rb:59:in `service'
/Users/Home/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/httpserver.rb:138:in `service'
/Users/Home/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/httpserver.rb:94:in `run'
/Users/Home/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:191:in `block in start_thread'

Anyone have any ideas? Any help would be greatly appreciated.

Start Sidekiq if not running automatically - Rails

I'm using redis server and sidekiq for my cron jobs but some time sidekiq kills automatically at backend.

I want to restart sidekiq from my controller's action or automatically restart when it kills down without stop my rails application server.

Please suggest me how can I manage this problem?

mardi 27 décembre 2016

ActionController::UnknownFormat Error for only format.js

I am simply using -

respond_to do |format|
    format.js
end

in my create action. Don't know why but i am getting an the UnknownFormat error. The error is gone if i put in both "format.html" and "format.js". But i want to stay in the same page and make an ajax call. I have gone through like 5 pages of google search results for every possible search and still nothing works for me. Can anyone help me out here?

My form is like this -

<%= form_for [:home, Photo.new], remote: true, :html => {:id => "new-photo-form"} do |f| %>

    <div id="upload-field">
        <%= f.file_field :image %>
    </div>

    <%= f.hidden_field :album_id, :value => album.id %>

    <div id="photo-add-link">
        <%= link_to 'Add Selected Images', '#', remote: true, :onclick => "$('#new-photo-form').submit()" %>
    </div>

<% end %>

rails : create children for given parent_id

i need your help to create parent-child relation.

i have a problem to make the create of the child working fine.

this is the model:

class Nccheklist < ActiveRecord::Base
  has_many :children, class_name: "Nccheklist", foreign_key: "parent_id"
  belongs_to :parent, class_name: "Nccheklist"

  def has_parent?
    parent.present?
  end

  def has_children?
    children.exists?
  end


end

the controller:

def create
    @nccheklist = Nccheklist.new(nccheklist_params)
    if @nccheklist.save
      redirect_to nccheklists_url, notice: 'Nccheklist was successfully created.'
    else
      render :new
    end
  end

and the view :

<%= form_for(@nccheklist) do |f| %>
  <% if @nccheklist.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@nccheklist.errors.count, "error") %> prohibited this nccheklist from being saved:</h2>

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

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
<div>
  <%= f.collection_select(:parent_id, @rootcat, :id, :name) %>
</div>
<br/><br/>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

when i submit the form, parent_id always equal null on database !

can someone help me please.

thanks.

savon gem SOAP-ERROR: Encoding: Violation of encoding rules

I am using savon version-2 gem for soap requests, and for authorization and few other urls i didnt face problem, but for particular endpoint i need to search the date range from and to which needs to be passed inside item so the problem is first item get replaced by second how do i avoid this

    client = Savon.client(wsdl: "http://ift.tt/2htBM2Y", log_level: :debug, pretty_print_xml: true, log: true)
    session = client.call(:login, message: {username: 'sss', apiKey: 'sss'})
    result = client.call(:sales_order_list, message: {sessionId: session.body[:login_response][:login_return], filters: {filter: {item: {key: 'created_at', value: {key: 'from', value: '2016-12-27 00:00:00'}}, item: {key: 'created_at', value: {key: 'to', value: '2016-12-27 23:59:59'}} }}})

the xml generated is like with the to value only and i get the error SOAP-ERROR: Encoding: Violation of encoding rules

I think overwriting items is the problem How do i send 2 items inside filter

How to get region in place of zipcode for UAE countries using google maps API?

When I get results then in this i am not getting region of the selected UAE area because in UAE there is no postal code/zipcode. if any way to get region for UAE areas then suggest me.

Below is my code:

var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  administrative_area_level_1: 'short_name',
  locality: 'long_name',
  postal_code: 'short_name'
};

var formComponentIds = {
  street_number: 'user_add_street',
  route: 'user_add_street',
  administrative_area_level_1: 'user_add_state',
  locality: 'user_add_city',
  postal_code: 'user_add_zipcode'
};

function initAutocomplete () {
  autocomplete = new google.maps.places.Autocomplete((document.getElementById('user_add_street')),{types: ['geocode']});
    autocomplete.addListener('place_changed', fillInAddress);
  $(document).on('focusout', '#pickupStreet', function() {
    var firstResult = $(".pac-container .pac-item:first").text();
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({"address":firstResult }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var lat = results[0].geometry.location.lat(),
        lng = results[0].geometry.location.lng(),
        placeName = results[0].address_components[0].long_name,
        latlng = new google.maps.LatLng(lat, lng);
        $('#pickup_latitude').val(lat);
        $('#pickup_longitude').val(lng); 
        debugger          
        for (var i = 0; i < results[0].address_components.length; i++) {
          if( results[0].address_components[i].types[0] == 'route'){
              $('#pickupStreet').val(results[0].address_components[i-1].long_name + " " + results[0].address_components[i].long_name);
          }
          else if (results[0].address_components[i].types[0] == 'locality'){
            $('#pickupCity').val(results[0].address_components[i].long_name);
          }
          else if (results[0].address_components[i].types[0] == 'administrative_area_level_1'){
            $('#pickupState').val(results[0].address_components[i].long_name);
          }
          // else if (results[0].address_components[i].types[0] == 'postal_code'){
          //   $('#pickupZipcode').val(results[0].address_components[i].long_name);
          // }
          else{
            console.log();
          }
        }
        $('#user_customer_detail_attributes_zipcode').val($('#pickupZipcode').val());
      }
    });
  });

}

function fillInAddress () {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();
  $('#pickup_latitude').val(place.geometry.location.lat());
  $('#pickup_longitude').val(place.geometry.location.lng());

  if (place.address_components) {
    for (var component in componentForm) {
      componentId = formComponentIds[component];
      document.getElementById(componentId).value = '';
      document.getElementById(componentId).disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      if (componentForm[addressType]) {
        var val = place.address_components[i][componentForm[addressType]];
        if (formComponentIds[addressType] == 'user_add_street') {
          var street = document.getElementById(formComponentIds[addressType]).value;
          document.getElementById(formComponentIds[addressType]).value = street + ' ' + val;
        } else {
          document.getElementById(formComponentIds[addressType]).value = val;
        }
      }
    }
    $('#user_add_street').val(place.name.split(','));
    document.getElementById('user_add_apartment_number') = '';
  } else {
    splitted_address = place.name.split(',');
    street = splitted_address[0];
    city = splitted_address[1];
    state = splitted_address[2];
    $('#pickupStreet').val(street);
    $('#pickupCity').val(city);
    $('#pickupState').val(state);
    $('#pickupZipcode').val('');
  }
}

Rails 5 Securing Action Cable with redis

What can I do to secure socket connection in rails 5 with redis and action Cable?

What configuration we can add in

config/redis.rb

to add password authentication in Redis.

Not able to place csv data in a Hash

I have a csv file with two columns:

PPS_Id Amount
123    100
1234   150

I read data from this file and insert in a array using the code below:

CSV.foreach("filename.CSV", headers: true) do |row|
file_details << row.inspect # hash
end

I am then trying to push the data in the file_details into a hash with PPS_Id as key and Amount as Value, I am using the code below:

file_details_hash = Hash.new
  file_details.each { |x|  
    file_details_hash[x['PPS_Id']] = x['Amount']
}

But when I print the result I get nothing just {"PPS_Id"=>"Amount"}

Can you please help

lundi 26 décembre 2016

Ruby on Rails routing error because of my root?

I just started using Ruby on Rails and I was following this guide and I was having trouble with 4.3 Setting the Application Home Page. It has you setting up the routes.rb like this -

Rails.application.routes.draw do
  get 'welcome/index'

  root 'welcome#index'
end

I have no idea what is wrong even tho it is simple, thanks for the help. ~Jimmy

dimanche 25 décembre 2016

Mailboxer validation

Hi where can I edit the mailboxer gem message validation settings? For example I'd like to restrict certain types of messages to be a certain length. Is there any way I can edit the inner models of the gem?

samedi 24 décembre 2016

Rails collection_check_boxes with Main type as well it's subtypes

Iam Working on an Event Management System, where i have HABTM between events and employees, I have created a checkbox with employees name like this,

<%= f.collection_check_boxes :employee_ids, Employee.all, :id,    
     :emp_name do |e| %>
       <div class="collection-check-box-subtypes">
       <%= e.check_box %>
           <%= e.label %>
       </div>
<%end%>  

but there are so many employees, therefore i want my employees to be selected by their department as well, so that it becomes more easy to select employees by departments rather than indiviually. And i also want to keep select all checkbox which is working right now perfectly. Therefore in short i want to create a checkbox like selectall/deselect all, than below the department name checkbox and under department the employees of that departments. Iam currently displaying the checkbox in front of the name of the departments, but it is not working as i want, below is the code: Select/Deselect All

  <% @employees.each do |department, employee|%>
  <input type="checkbox" name="" value="selectDepartment" id="selectDepartment">
    <label for="selectDepartment">
      <%= department.name%>
    </label><br>
      <div class="field">
        <div class="sub_check_box">
          <%= f.collection_check_boxes :employee_ids, employee, :id, :emp_name do |e| %>
              <div class="collection-check-box-subtypes">
                <%= e.check_box %>
                <%= e.label %>
              </div>
          <%end%>  
        </div>
      </div>
  <%end%>

Please if anyone can help me.

prawn bounding box get remaining height

I have been following this stack answer for content overflow, from one column to another, The problem i face is, i cannot get the current position of the cursor inside the bounding box. So that i could do calculation to get the remaining height in bounding box and set it to the next text box, currently it overflows the bounding box.

bounding_box([175, starting_y - 240], :width => 30.mm, :height => 67.5.mm) do
  transparent(1) { stroke_bounds }
  indent 5,5 do 
    column_box([0, cursor], columns: 1, width: bounds.width) do
      text "#{cursor}"
      text "XS", align: :center, inline_format: :true
      text "XS", align: :center, inline_format: :true
      text 'XS', align: :center, inline_format: :true
      text 'aaaa', align: :left
      text "<b> asda </b>: #{sec_call}", inline_format: true
    end
    column_box([0, cursor], columns: 5, width: bounds.width, height: 0.27.cm) do
      image open('http://ift.tt/2hSZuoh'), width: 0.27.cm
      image open('http://ift.tt/2hSZuoh'), width: 0.27.cm
    end
    column_box([0, cursor], columns: 1, width: bounds.width) do
      text "#{care_instr.upcase}"
      text "#{imported_for}"
      text "CA 17897"
      text "FABRIQUE EN CHINE/ HECHO EN"
      text "CHINA"
    end
    # span(bounds.width, position: :left) do
    #   text_box "#{care_instr.upcase}", at: [180, cursor], overflow: :truncate, :width => 25.mm
    #   text_box "#{imported_for}", at: [180, cursor-45], overflow: :truncate, :width => 25.mm
    # end
    span(bounds.width, position: :left) do
      text_to_write = text_box text_to_write, at: [180, cursor], overflow: :truncate, :width => 25.mm, :height => 50.5.mm
    end
  end
end

text_to_write is a long text which needs to be carried to next column which is working fine, sometimes the "#{sec_call}" value increaes so the text to write overlaps/overflows the table, so i need to dynamically change the height so it flows correctly to next column.

Whenever i print cursor inside bounding box it says 0.0, the bounding box height is static and its position also is there any way to calculate the remaining space inside bounding box from current position

vendredi 23 décembre 2016

Signup in alfersco for accessing cloud services

I want integrate my rails application with alfersco for documentation service. I want secret_access_key for accessing alfersco functionalities. I try to signup in following url(http://ift.tt/2h6fGTX) but it didn't gave any response and render the same page. If any link signup as a developer into alfersco.

Unit testing a polymorphic association with fixtures in rails 4

I need to unit test a promotions model where every campaign has a URL. There is a polymorphic association between promotions and reference_link. the reference link fixture reference_link: linkable: fix_1 (PromoCode)

How do I convince rails that the promotions fixture does indeed have a URL belonging to it?

In promotions test helper

test "should have a URL associated with the promo code" do
promo_code = promo_codes(:fix_1)
promo_code.reference_link.url = nil
assert_not promo_code.valid?
promo_code2 = promo_codes(:fix_2)
assert promo_code2.valid?

end

promocode.rb

class PromoCode < ActiveRecord::Base

belongs_to :reward
has_one :reference_link, as: :linkable, dependent: :destroy

validates :email, presence: true
validates :code, presence: true

end

reference_link.rb

class ReferenceLink < ActiveRecord::Base belongs_to :linkable, polymorphic: true,touch: true

 validates :link_name, presence: true
 validates :link_url, presence: true 

 validates_format_of :link_url, :with => /\A#{URI::regexp(['http',    'https'])}\z/

validates_length_of :link_url,:link_name, :maximum => 255  

end

Account deleted move all posts from that account to default admin account

first of thank you all for taking the time reading this and answering.

i'm trying to find example or at least some help with the logic,

what i'm trying to do, is after a user removes his/her account to automatically transfer any resources to default admin account.

Using devise for user management.

Not sure what you might need to know more on this to be able to help out, But let me know and i shall provide more information.

Thank you in advance!

bundle exec rake error

I am trying to setup harry's referral system http://ift.tt/1pwW30B on aws server. While setting up database using postgresql and after submitting command bundle exec rake db:create, it gives me following error:

 fe_sendauth: no password supplied

/home/ubuntu/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.5.2/lib/active_record/connection_adapters/postgresql_adapter.rb:651:in initialize' /home/ubuntu/.rvm/gems/ruby-2.3.0/gems/activerecord- /home/ubuntu/.rvm/gems/ruby-2.3.0/bin/rake:23:inload' /home/ubuntu/.rvm/gems/ruby-2.3.0/bin/rake:23:in <main>' /home/ubuntu/.rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:ineval' /home/ubuntu/.rvm/gems/ruby-2.3.0/bin/ruby_executable_hooks:15:in `' Couldn't create database for {"adapter"=>"postgresql", "database"=>"prelaunchr_test", "host"=>"localhost"}

Admin Conditions In Devise with Rails 5

I have created an admin user in my app by adding a giving admin a boolean value. The problem is when i set a user to be admin , they can't delete or edit the post in the app although i have set a condition in the show page of the post. Note that i am using the Deivse gem for user authentication. Here's my code:

BurgersController.rb

class BurgersController < ApplicationController
  before_action :authenticate_user! , except: [:index,:show,:search]
  before_action :set_burger, only: [:show, :edit, :update, :destroy,:upvote]
  before_action :check_user , only: [:edit,:update,:destroy]


  # GET /burgers
  # GET /burgers.json

   def search
    if params[:search].present?
    @burgers = Burger.search(params[:search])
    else
    @burgers = Burger.all
    end
  end
    def index
     if params[:tag]
      @burgers = Burger.tagged_with(params[:tag])
    else
      @burgers = Burger.all
    end
  end

  # GET /burgers/1
  # GET /burgers/1.json
  def show
  end

  # GET /burgers/new
 def new
    @burger = Burger.new
  end

  # GET /burgers/1/edit
  def edit
  end

  # POST /burgers
  # POST /burgers.json
  def create
    @burger = Burger.new(burger_params)
    @burger.user_id = current_user.id

    respond_to do |format|
      if @burger.save
        format.html { redirect_to @burger, notice: 'Burger was successfully created.' }
        format.json { render :show, status: :created, location: @burger }
      else
        format.html { render :new }
        format.json { render json: @burger.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /burgers/1
  # PATCH/PUT /burgers/1.json
  def update
    respond_to do |format|
      if @burger.update(burger_params)
        format.html { redirect_to @burger, notice: 'Burger was successfully updated.' }
        format.json { render :show, status: :ok, location: @burger }
      else
        format.html { render :edit }
        format.json { render json: @burger.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /burgers/1
  # DELETE /burgers/1.json
  def destroy
    @burger.destroy
    respond_to do |format|
      format.html { redirect_to burgers_url, notice: 'Burger was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def upvote
      @burger.upvote_by current_user
    redirect_to :back
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def burger_params
      params.require(:burger).permit(:name, :resturant, :place, :price,:image,:tag_list)
    end

    def check_user
      unless @burger.user == current_user || current_user.admin?
        redirect_to root_url , alert: "Sorry this listing belongs to someone else"
      end
    end

end

views/burger/show.html.erb

 <div class="row">
      <div class="col-md-12">
        <div class="thumbnail">  
            <%= image_tag @burger.image_url.to_s, class: 'center-block'%>
        </div>

      </div>
        <div class="col-md-6">
            <h2><%= @burger.name %><br></h2>
            <%= @burger.resturant %><br>
            <%= @burger.place %><br>
            <%= number_to_currency(@burger.price, raise: true) %><br>
          <p>Tags: <%= @burger.tag_list %></p>
        </div>



      </div>
     <% if user_signed_in? && current_user == @burger.user || current_user.try(:admin?) %>
      <%= link_to 'Edit', edit_burger_path(@burger) %> |
      <%= link_to 'Back', burgers_path %>
      <%= link_to 'Delete', @burger, method: :delete, data: {confirm: "Are you Sure ?"} %>
      <%end%>

    </div>

</div>

schema.rb

create_table "users", force: :cascade do |t|
    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.datetime "created_at",                             null: false
    t.datetime "updated_at",                             null: false
    t.string   "name"
    t.boolean  "admin",                  default: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

Can't install gem 'jumpstart_auth' (Screenshot posted as well)

Screenschot of the error in my terminal

I am trying to install the gem however it wont let me due to some error , tried reading the gem documentation but couldn't figure it out myself.Thats when I needed the help of the seasoned ones.

Building native extensions. This could take a while... ERROR: Error installing jumpstart_auth: ERROR: Failed to build gem native extension.

current directory: /var/lib/gems/2.3.0/gems/http_parser.rb-0.6.0/ext/ruby_http_parser

/usr/bin/ruby2.3 -r ./siteconf20161223-26375-4etqmc.rb extconf.rb mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.3.0/gems/http_parser.rb-0.6.0 for inspection. Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/http_parser.rb-0.6.0/gem_make.out

How to get Conditional Groups in Ransack?

Using Railscast and Ransack demo code, I am able to build Advanced Search like this

enter image description here

The drop down "all/any" comes from <%= f.combinator_select %> and it works but I need Conditional Groups with (X AND Y) OR (A AND B) AND (M OR N) etc which I am not able to get.

I saw the Ransack Demo example multiple times but it is using Rails 5 and I am not very clear with some part of it.

Here is my code in Rails 4, can you tell me how to get Conditional Grouping ?

routes.rb

resources :data do
  collection do
    get :search
    post :search, to: 'data#search'
  end
end

data.rb

   def search

        @search = Data.search(params[:q])
        @datum = @search.result(:distinct=>true).paginate(page: params[:page], per_page: 10)

        if params[:q].nil?
            @datum = Prospect.where(:id => 0).paginate(page: params[:page], per_page: 10)
        end

        @page = params[:page] || 0
        @pids = @search.result(:distinct=>true).pluck(:id)

        @search.build_condition
    end

search.html.erb

<div class="row">
    <div class="col-lg-10">
        <div class="form_search">
            <%= search_form_for @search, url: search_data_index_path, html: { method: :get, class: "data_search" } do |f| %>
            <%= f.condition_fields do |c| %>
            <%= f.combinator_select %>
            <%= render "condition_fields", f: c %>
            <% end %>
            <p><%= link_to_add_fields "Add Conditions", f, :condition %></p>
            <br>
            <div class="actions">
                <%= f.submit "Search", :class => "btn btn-primary" %>
            </div>
            <% end %>
        </div>
    </div>
</div>

_condition_fields.html.erb

<div class="field">
    <%= f.attribute_fields do |a| %>
    <%= a.attribute_select associations: [:user, :data] %>
    <% end %>
    <%= f.predicate_select %>
    <%= f.value_fields do |v| %>
    <%= v.text_field :value %>
    <% end %>
    <%= link_to "remove", '#', class: "remove_fields" %>
</div>

jeudi 22 décembre 2016

I am having problems with my views displaying my model

in this application, clients can have many projects and projects can only have one client.

I keep getting this error:

ActionController::ParameterMissing in ProjectsController#new

param is missing or the value is empty: project

this is the line that is highlighted in my project controller:

params.require(:project).permit(:client_id, :project_description, :project_timescale)

this is my client model:

class Client < ActiveRecord::Base
has_many :projects, dependent: :destroy
validates :name, presence: true
end

this is my project model:

class Project < ActiveRecord::Base
belongs_to :client
validates :project_description, :client, presence: true
end

these are my migration for the client

class CreateClients < ActiveRecord::Migration
def change
create_table :clients do |t|
  t.string :name, presence: true, null: false

  t.timestamps null: false
 end
end
end

migration for the projects:

class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
  t.belongs_to :client, index: true, foreign_key: true, null: false
  t.text :project_description, null: false, presence: true
  t.string :project_timescale

  t.timestamps null: false
end
end
end

the controller for the client:

class ClientsController < ApplicationController
before_action :set_client, only: [:show, :edit, :update, :destroy]

# GET /clients
# GET /clients.json
def index
@clients = Client.all
end

# GET /clients/1
# GET /clients/1.json
def show
end

# GET /clients/new
def new
@client = Client.new
end

# GET /clients/1/edit
def edit
end

# POST /clients
# POST /clients.json
def create
@client = Client.new(client_params)

respond_to do |format|
  if @client.save
    format.html { redirect_to @client, notice: 'Client was successfully     created.' }
    format.json { render :show, status: :created, location: @client }
  else
    format.html { render :new }
    format.json { render json: @client.errors, status: :unprocessable_entity }
  end
  end
  end

  # PATCH/PUT /clients/1
  # PATCH/PUT /clients/1.json
  def update
  respond_to do |format|
  if @client.update(client_params)
    format.html { redirect_to @client, notice: 'Client was successfully updated.' }
    format.json { render :show, status: :ok, location: @client }
    else
    format.html { render :edit }
    format.json { render json: @client.errors, status: :unprocessable_entity }
    end
    end
    end

   # DELETE /clients/1
   # DELETE /clients/1.json
   def destroy
   @client.destroy
   respond_to do |format|
   format.html { redirect_to clients_url, notice: 'Client was successfully destroyed.' }
   format.json { head :no_content }
   end
   end

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

   # Never trust parameters from the scary internet, only allow the white list through.
   def client_params
   params.require(:client).permit(:name)
   end
   end

controller for the project:

    class ProjectsController < ApplicationController
    before_action :set_project, only: [:new, :create]

    # GET /projects
     # GET /projects.json
  def index
    @projects = Project.all
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
  end

  # GET /projects/new
  def new
    @project = @client.projects.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    @project = @client.projects.new(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project, notice: 'Project was successfully created.' }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project, notice: 'Project was successfully updated.' }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url, notice: 'Project was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = Client.find_by(id: params[:client_id]) || Client.find(project_params[:client_id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
       params.require(:project).permit(:client_id, :project_description, :project_timescale)
    end
end

Ruby on Rails Nested Attribute form broken, Database Rollback, error is not clear

I am still very new to Ruby on Rails so forgive me if the answer is obvious.

I am building an app with 3 models (User, Bundle, Entry) that have the following relations and for some reason, when I try to create a new Bundle with an entry while logged in as a user, I get some error (but I don't even see what the error is).

If I create a new bundle without the entry, it works as expected. And if I try to make a bundle from the rails console, it also works fine.

All I can discern is that whenever I try to create a new bundle and a new entry from the browser, I get a flash on the top of the screen (from flash[:danger] inside bundles#create) and this message in the console:

Started POST "/bundles" for ::1 at 2016-12-22 18:07:28 -0500
Processing by BundlesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"ATsxcPqsH9whw3Jp/GgkNFgGR7ep2142ZRH27nLWpe/QSkvxSvNQOmerRVGa5ZlYaWJ99/NqlTVusqmlisBviA==", "bundle"=>{"name"=>"first", "entries_attributes"=>{"0"=>{"title"=>"bundle name", "url"=>"www.facebook.com", "_destroy"=>"0"}}}, "commit"=>"Add"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
  Rendered users/_user.html.erb (0.9ms)

Here are my models:

bundle.rb .

class Bundle < ApplicationRecord
  belongs_to :user
  has_many :entries, dependent: :destroy, inverse_of: :bundle
  accepts_nested_attributes_for :entries, reject_if: ->(attrs) { attrs['title'].blank? || attrs['url'].blank? }, allow_destroy: true

user.rb

class User < ApplicationRecord
  has_many :bundles, dependent: :destroy
  has_many :entries, through: :bundles

entry.rb

class Entry < ApplicationRecord
  belongs_to :bundle
  has_many :users, through: :bundle

Inside users#show, my view looks like this:

user show view: a list of user's bundles and a form to submit a new bundle

Here are my controller actions:

bundles_controller.rb

    def create
        @bundle = current_user.bundles.build(bundle_params)
        if @bundle.save
          flash[:success] = "Bundle Created!"
          redirect_back_or current_user
        else
          flash[:danger] = "Something went wrong"
          render current_user

        end
      end
private
    def bundle_params
        params.require(:bundle).permit(:name, entries_attributes: [:id, :title, :url, :_destroy])
    end

users_controller.rb

  def show
    @user = User.find(params[:id])
    @bundles = @user.bundles
    @bundle = current_user.bundles.new if logged_in?
    @bundle.entries.build
  end

entries_controller.rb

      def create
        @new_entry = Entry.new(entry_params)
        if @new_entry.save
          redirect_back_or root_path
        else
          render 'index'
        end


        end
private
      def entry_params
        params.require(:entry).permit(:title, :url)
      end

And here is the code for the form itself: _bundle_form.html.erb

   <%= form_for(@bundle) do |f| %>
        <%= render 'shared/error_messages', object: f.object %>
        <div class="field" >
          <%= f.text_area :name, placeholder: "Bundle name" %>
        </div>

        <div>
          <p><strong>Entries:</strong></p>
          <%= f.fields_for :entries do |entry| %>

                <%= entry.label :title %>
                <%= entry.text_area :title, placeholder: "title" %>
                <%= entry.text_area :url, placeholder: "URL" %>

          <% end %>
        </div>

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

Thanks for any help anyone here might be able to offer.

Address validation regex. What does this Rails validation mean?

I have a Rails validation that reads:

validates :address_line_1, format: {
    if: :changed?,
    without: /^[0-9]+$/,
    multiline: true,
    message: I18n.t(
      :missing_street_info, scope: 'activerecord.errors.models.address'
    )
  }

What does the without section mean? What is that regex? What is the multiline key mean?

I am not able to format the string to get desired result

I have a method that return string in the view. I am not able the format the string to desired output.

return_string = ""
test = {
      "1"=>{:name=>"joe", :age=>"1", :model=>"ABCD-000D4"}, 
      "2"=>{:name=>"Dav", :age=>"2", :model=>"EFGH-000D3"}, 
      "5"=>{:name=>"Pok", :age=>"5", :model=>"EFGH-000D3"}, 
      "4"=>{:name=>"Lan", :age=>"4", :model=>"EFGH-000D3"}, 
      "3"=>{:name=>"Bas", :age=>"3", :model=>"EFGH-000D3"},
      "6"=>{:name=>"Kit", :age=>"6", :model=>"ABCD-000D4"},
      "7"=>{:name=>"Sop", :age=>"7", :model=>"ABCD-000D4"}
       }
test.keys.each do |age|
  return_string += "AGE: #{age} = <b><font color='blue'>Model: #{test[age][:model]}</font></b><br/>"
end

Output I am getting now:

AGE: 1 = Model: ABCD-000D4
AGE: 2 = Model: EFGH-000D3
AGE: 5 = Model: EFGH-000D3
AGE: 4 = Model: EFGH-000D3
AGE: 3 = Model: EFGH-000D3
AGE: 6 = Model: ABCD-000D4
AGE: 7 = Model: ABCD-000D4

Desired Output

AGE: 1 = Model: ABCD-000D4
AGE: 2-5 = Model: EFGH-000D3
AGE: 6-7 = Model: EFGH-000D4

mercredi 21 décembre 2016

Ruby Nested Form

Actually, On saving it must save, but i am getting error and tried to figure out the error where i did mistake.

Kindly help me with this error.

Thanks in Advance.

Controller

def new
  @fooditem = Fooditem.new
  3.times { @fooditem.fooditemprices.build}
end

#Creating Food Items
def create
    @fooditem = Fooditem.new(fooditem_params)
    if @fooditem.save
        flash[:success] = "Food item created successfully."
        redirect_to fooditems_path
    else
        render 'new'
    end
end

Model(s)

class Fooditem < ApplicationRecord
  has_many  :fooditemprices, dependent: :destroy
  accepts_nested_attributes_for :fooditemprices, reject_if: lambda {|attributes| attributes['price'].blank?}, allow_destroy: true
end

class Fooditemprice < ApplicationRecord
  belongs_to :fooditem

  validates :size, presence: { message: "Size must exists." }
  validates :price, presence: { message: "Price must exists." }
end

Form data

<%= f.fields_for :fooditemprices do |ftp_form| %>
 <div class="col-sm-9 row col-sm-offset-3">
   <div class="col-sm-3">  
     <%= ftp_form.select :size, ["Full", "Half", "Small", "Medium", "Large"].collect { |p| [p, p] },{}, {class: "form-control"} %>
   </div>     
   <div class="col-sm-3">
      <%= ftp_form.number_field :price, placeholder: "Price", class: "form-control" %>
   </div>
   <div class="col-sm-3">      
      <%= ftp_form.number_field :weight, placeholder: "Weight", class: "form-control" %>
   </div>                
   <div class="col-sm-3">               
      <%= ftp_form.select :weight_in, ["Grams", "ml"].collect { |p| [p, p] },{}, {class: "form-control"} %>
   </div>
  </div>
<% end -%>

Error

fooditem must exist

Assigning multiple sql result values to the same key

I have a sql result of this form:

Id Amount1 Amount2 Amount3
1  10      10       12
2  20      13       14
3  30      15       15

I am trying to store the Id in Key and all other values in value

something like this:

{1=>{:Amount1=>"10", :Amount2=>"10", :Amount3=>"12"}, 2=>{:Amount1=>"20", :Amount2=>"13", :Amount3=>"14"}}

This is what I currently have so far:

hashn = Hash.new

  sqlresult.each { |x|  
    hashn[x['PPS_Id']] = x['Gift_Card_Amount1']
    hashn[x['PPS_Id']] = x['Gift_Card_Amount2']
    hashn[x['PPS_Id']] = x['Gift_Card_Amount3']
}

I believe this overrides the previous value can you please help.

How to sort hash in rails

I have a hash

x= {
  "1"=>{:name=>"test1", :age=>"1"}, 
  "5"=>{:name=>"test2", :age=>"5"}, 
  "2"=>{:name=>"test3", :age=>"2"}, 
  "4"=>{:name=>"test4", :adn=>"4"}, 
  "3"=>{:name=>"test5", :adn=>"3"}
 }

Desired output

x= {
  "1"=>{:name=>"test1", :age=>"1"}, 
  "2"=>{:name=>"test3", :age=>"2"}, 
  "3"=>{:name=>"test5", :age=>"3"}, 
  "4"=>{:name=>"test4", :adn=>"4"}, 
  "5"=>{:name=>"test2", :adn=>"5"}
 }

What I have so far, I tried doing x.sort.flatten and i got

[
  "1", {:name=>"test1", :age=>"1"}, 
  "2", {:name=>"test3", :age=>"2"}, 
  "3", {:name=>"test5", :adn=>"3"}, 
  "4", {:name=>"test4", :adn=>"4"}, 
  "5", {:name=>"test2", :age=>"5"}
]

Clearing part of the Rails cache and not all of it with Rails.cache.clear

I'm trying to clear part of my rails cache. My problem is that there are logs that are being cached that need to be cleared but if I clear the whole cache active users will be logged out of the site.

Can't SUM DISTINCT values in Ruby on Rails

I have 4 tables: Users, Workouts, Exercises, and Results. A "User" posts "Results" for "Exercises" which are linked to a single "Workout". But when the user posts results, since there are multiple exercises, results for one workout can be linked with a unique "post_id". I would like to know how many total minutes a user exercised based on how many "post_ids" they provided which can be linked to the "Workouts" table where a "workout_duration" column shows how many minutes each workout lasts. Here is some sample data, where in this case the workout (workout_id=1) has two exercises and has a workout_duration of 1 minute.

Results:

user_id| workout_id| post_id| exercise_id| number_of_reps|
-------+-----------+--------+------------+---------------+
    123|         1 |       1|          1 |             18|
    123|         1 |       1|          2 |             29|      
    123|         1 |       2|          1 |             15|
    123|         1 |       2|          2 |             30|
    123|         1 |       3|          1 |             20|
    123|         1 |       3|          2 |             28|
-------+-----------+--------+------------+---------------+

Workouts:

workout_id| workout_duration|
----------+-----------------+
         1|                1|

I tried to retrieve the total number of minutes based on the query below, but it is returning a sum of 6 when I want it to return a value of 3...I think this is because the SUM is not taking into account DISTINCT post_ids...rather it is just summing all post_ids.

@user = User.find(current_user)
@total_minutes = @user.results.includes(:workout).select(:post_id).distinct.sum(:workout_duration)

I have searched high and low for solutions to no avail...any ideas?

BSON::InvalidObjectId illegal ObjectId format Rails 3.1.1

I'm getting the following error when trying to use the delete method in a Ruby on Rails application.

BSON::InvalidObjectId in ServicesController#destroy

I'm using Rails 3.1.1 and MongoDB v2.4.15

Below is the Delete link in question.

%li= link_to 'Delete', @service, :method => :delete, :confirm => "Are you sure you want to delete this service?"

Here is the log error:

Started DELETE "/services/appeals" for 127.0.0.1 at 2016-12-21 11:08:42 -0500
Creating scope :orderable_scope. Overwriting existing method Service.orderable_scope.
  Processing by ServicesController#destroy as HTML
  Parameters: {"authenticity_token"=>"xxx", "id"=>"appeals"}
Completed 500 Internal Server Error in 11ms

BSON::InvalidObjectId (illegal ObjectId format: appeals):

When deleting items in other collections it works fine. I'm able to use the "services" edit link without errors. Below is the working Delete link and logs for deleting an attorney.

Working Link %li= link_to "Delete", @attorney, :method => :delete, :confirm => "Are you sure you want to delete this attorney?"

Working Log

Started DELETE "/attorneys/first-last" for 127.0.0.1 at 2016-12-21 10:37:07 -0500
Creating scope :orderable_scope. Overwriting existing method Attorney.orderable_scope.Processing by AttorneysController#destroy as HTMLParameters: {"authenticity_token"=>"xxx", "id"=>"first-last"}
MONGODB x_development['system.namespaces'].find({})
MONGODB x_development['attorneys'].find({:slug=>"first-last"}).limit(-1).sort([[:_id, :asc]])
MONGODB x_development['system.namespaces'].find({})
MONGODB x_development['users'].find({:_id=>BSON::ObjectId('585a9dbc737da97cbd000006')}).limit(-1).sort([[:_id, :asc]])
Creating scope :orderable_scope. Overwriting existing method Service.orderable_scope.
MONGODB x_development['system.namespaces'].find({})
Redirected to http://ift.tt/2hHOsSB
Completed 302 Found in 69ms` 

It's another developers application that I'm trying to get working correctly again. I'm not very experienced with Ruby, Rails, or MongoDB.

SETTING UP A CLOUDFRONT CDN FOR RAILS

I setting up the cloudfront CDN for rails but its not working.

My site is on ec2.

I do following steps.

For http://ift.tt/2a9q2eA

  1. Create Distributions
  2. Add ec2 URL in the Origin Domain Name
  3. Submit the distributions and It's display me below (See attachment)

enter image description here

For Ruby on Rails side

  1. In production.rb file, I added below line

    config.action_controller.asset_host = "CDN-DOMAIN-NAME.cloudfront.net"

  2. Restart the application and Testing.

But it's not working. When I open CDN url in another tab then it's redirect to my ec2 URL site. I think that is the problem.

So can any one help me what's the problem and why it's redirect to my ec2 URL site?

Splitting values in Hashmap

I have a hashmap in the following format:

{"PPS_Id"=>["fe4d7c06-215a-48a7-966d-19ab58976548", "6e90208e-4ab2-4d44-bbaa-9a874bff095b"], "Amount"=>"[#<BigDecimal:7fcb1e0904c0,'0.1E5',9(18)>, #<BigDecimal:7fcb1e08a4a8,'0.2374E4',9(18)>]"}

When I write this data into an excel get the following output. enter image description here I want to write the data into the Excel this way:

PPS_Id                                     Amount
fe4d7c06-215a-48a7-966d-19ab58976548       12345
6e90208e-4ab2-4d44-bbaa-9a874bff095b       12345

How do I convert my current Hash to the below:

{PPS_Id"=>["fe4d7c06-215a-48a7-966d-19ab58976548","Amount"=>"12345"},{PPS_Id"=>["6e90208e-4ab2-4d44-bbaa-9a874bff095b","Amount"=>"12345"}

Also, when I use .value.to_s to convert the BigDecimal value in hash to an integer, It doesn't seem to work.

Can you please assist.

mardi 20 décembre 2016

Notifying user of a new feature through one time notification in ruby on rails

I want to inform users of a new feedback feature the very next time they log in and never after that unless they opt the option of "Later maybe".

How can I achieve it? Thanks in advance.

How .to_day fixed my date issue

We have a build that runs all the ruby files including unit_tests. Build is configured at UTC time and our database inserts records based on CST timezone because config.time_zone property in application.rb is set to CST timezone.

My unit tests had start_date: 50.days.ago and when i ran build it'll pass anytime during day before 7 PM. After 7 PM per build UTC time its next day. I mean if i start build at 7:10PM, build will show 12:10 AM and it'll fail.

I changed start_date: 50.days.ago.to_date and it doesnt fail now. Can someone explain me why it worked using to_date?

Two has_many relationship through same model

I'm facing a problem that I'm not figuring out how to solve it.

I have three models

  • Teacher
  • Rooms
  • Hours

I need to associate them through the same model. By now I have a 4th model called schedules which I have two foreign keys. teacher_id and hour_id, which is working perfectly, but I also need to associate rooms through this model.

Here is my code:

teacher.rb

class Teacher < ApplicationRecord
  scope :active, -> {where(deleted_at: nil)}
  has_many :schedules, dependent: :destroy
  has_many :lesson_hours, through: :schedules
  has_many :teacher_courses, dependent: :destroy
  has_many :courses, through: :teacher_courses
  has_many :registrations

  def check_associations
    errors.add(:base, "Há matrículas cadastradas com esse professor. Por favor ajuste antes de deletar.") if self.registrations.active.count > 0
    return errors.blank?
  end

  def delete!
    if check_associations
      self.deleted_at = Time.current
      save!
      return true
    else
      return false
    end
  end
end

room.rb

class Room < ApplicationRecord
  scope :active, -> {where(deleted_at: nil)}
  has_many :room_courses, dependent: :destroy
  has_many :courses, through: :room_courses
  has_many :registrations

  def check_associations
    errors.add(:base, "Há matrículas cadastradas com essa sala. Por favor ajuste antes de deletar.") if self.registrations.active.count > 0
    return errors.blank?
  end

  def delete!
    if check_associations
      self.deleted_at = Time.current
      save!
      return true
    else
      return false
    end
  end
end

lesson_hour.rb

class LessonHour < ApplicationRecord
  scope :active, -> {where(deleted_at: nil)}
  has_many :schedules, dependent: :destroy
  has_many :teachers, through: :schedules
  has_many :registrations

  def check_associations
    errors.add(:base, "Há matrículas cadastradas nesse horário. Por favor ajuste antes de deletar.") if self.registrations.active.count > 0
    return errors.blank?
  end

  def delete!
    if check_associations
      self.deleted_at = Time.current
      save!
      return true
    else
      return false
    end
  end
end

schedule.rb

class Schedule < ApplicationRecord
  belongs_to :teacher
  belongs_to :lesson_hour
end

All these associations are being constructed through a form in TeachersController

teachers_controller.rb

def set_lesson_days_and_hours
    @lesson_days = LessonHour.select(:weekday)
                             .group(:weekday)
                             .order(:weekday)
                             .to_a
    @lesson_hours = {}
    @lesson_days.each do |ld|
      @lesson_hours[ld.weekday] = LessonHour.active
                                            .select(:id, :start_time)
                                            .order(:start_time)
                                            .where(weekday: ld.weekday)
    end
  end

  def teacher_params
    params
      .require(:teacher)
      .permit(:name, :address, :address_number, :address_complement,
              :address_cep, :address_neighborhood, :city, :state, :birthdate,
              :email, :cpf, :rg, :phone, :mobile, :started_date, :bank, :agency,
              :account_number, :gender, lesson_hour_ids: [], course_ids: [])
  end

And the form to link lesson_hour to teacher is the following:

<div class="row teacher-schedule">
    <h4>Disponibilidade</h4>

    <% @lesson_days.each do |ld| %>
    <div class="col-md-2 one-per-line teacher-schedule">
      <span><strong><%= t(:"date.day_names")[ld.weekday] %></strong></span>
      <%= f.collection_check_boxes(:lesson_hour_ids, @lesson_hours[ld.weekday], :id, :start_time) do |check_box| %>
      <%= check_box.label class:"label-checkbox" do %>
      <%= check_box.check_box + check_box.text.strftime("%H:%M") %>
      <% end %>
      <% end %>
    </div>
    <% end %>
  </div>

So, my question is, how can I include room association in schedule model?

Thanks in advance

I am not able to load layout while rendering in rails

can anybody help me out , why i am not able to load particular layout for particular action with
render :layout => "application"
application.html.erb present in layouts folder.
is i have to do some settings for layout?

my code is :-

class PageController < ApplicationController
layout false
def index1
render :layout => "application"
end
end

Auto fill doesn't work on edit with image uploader

I trying to create a blog with a obligatory image, but after create, when i try to edit this blog, his image appears on thmbnail but not in field and i have to select the image again.

For upload image i use the carrierwave gem.

My model

class Blog < ActiveRecord::Base
validates :name, :description, :picture, presence: true

mount_uploader :picture, BlogPictureUploader

def picture_url
  picture.url
end

My view

= simple_form_for [blog] do |f|
 .row
  .col-md-6
    .panel.panel-default
      .panel-heading Foto
      .panel-body
        .thumbnail class="#{blog.picture? ? "" : "hide"}"
          = image_tag blog.picture
        p= f.input :picture, label: 'Selecione a foto:', hint: 'A foto deve ter 270x270.'

My controller

 class BlogsController < ApplicationController
 expose(:blog, attributes: :blog_params)

 def update
   authorize blog
   blog.save
   respond_with blog, location: [:blog]
 end

The behavior on edit: edit view after click button

Will "bundle upgrade" upgrade all the gems on system or just once in Gemfile?

I have cloned a rails app which is having Rails 5 along with some newer gems. Now I can't run it with "bundle" or "bundle install" as it is showing me a message to do "bundle update".

Since I have many running apps on my current system using older Rails 4 and older gems, I want to make sure bundle update don't mess other apps, current rails version, various gems and losing existing gems and configuration and uninstalling/rolling back can be time consuming.

Is it safe to run 'bundle update' without it affecting any other apps and gems ?

lundi 19 décembre 2016

Rails3. Create new record in db using 2 ids

Db Cart must have user_id, product_id. There is some method like

 @user = current_user
 @photo = @user.photos.build(params[:photo])

for creating new record but using 2 ids?

Running the Rails Application with rails version 2.3.2 on Rails 5 configured environment

I have install rails 5 and create the application successfully. But I have an application which is created on rails 2.3.2, Do I able to test the application on my machine, which have rails 5

I have try to create an application (rails _2.3.2_ new my_app) using rails 2.3.2 version for this I got the following error. That is railties not found. How do I fix this

/home/techorin/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/dependency.rb :319:in `to_specs': Could not find 'railties' (= 2.3.2) - did find: [railties-5.0.0.1,railties-4.2.6,railties-4.2.1,railties-4.1.2] (Gem::LoadError)
Checked in 'GEM_PATH=/home/techorin/.gem/ruby/2.3.0:/home/techorin/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0', execute `gem env` for more information
from /home/techorin/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/dependency.rb:328:in `to_spec'
from /home/techorin/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_gem.rb:65:in `gem'
from /home/techorin/.rbenv/versions/2.3.1/bin/rails:22:in `<main>'

How to write select statement in rails controller

I want to get only specific column details from ActiveRecord. So i did run the following code.

accounts = self.accounts(:select => "id, name,account_number").order("created_at DESC").paginate(:page => page_count, :per_page => per_page_count)

Whenever this line is getting executed its firing this following query

SELECT "accounts".* FROM "accounts" INNER JOIN "super_account_accounts" ON "accounts"."id" = "super_account_accounts"."account_id" WHERE "super_account_accounts"."super_account_id" = 8 ORDER BY accounts.created_at DESC LIMIT 10 OFFSET 0

Why it is getting all the column information when i have already specified few of the columns for which i want the info.

NOTE:- Super account model has the following association with account has_many :accounts, :through => :super_account_accounts, :dependent => :destroy account model has the following association with super account has_many :super_accounts, :through => :super_account_accounts

dimanche 18 décembre 2016

add headers authorization for token, token not showing on request header when i run my application in production

i try to add headers authorization for my application, it's working well when i try run my code on development env..

but i got error (unauthorized) when i try on production env.. when i inspect on chrome->network->headers, the token headers that i set not showing on there.. any one know how to fix it?

this is how i wrote the headers mycode.coffe :

$http.get("/api/#{type}?#{$.param(queryParams)}", ignoreLoadingIndicator: params.ignoreLoadingIndicator, headers: "X-API-TOKEN": "a681ff302f5b5b7fab18d6efe8b2541e375a565678c0b040")
      .then (response) ->
          data = response.data

i don't know why that X-API-TOKEN not showing when i run my application on production env.. but it's showing when i run on development env..

thank you very much..

this is prod env:

enter image description here

this is develop env:

enter image description here

How does "user = users(:michael)" work in Michael Hartl's Rails tutorial?

I don't understand how: user = users(:michael)

works, for instance in Listing 12.12 here: http://ift.tt/2hXzn04

Does this have something to do with the .yml file? What is this method of creating users called?

Rails dropdown menu - assign parameter for path from the user's selection

I want this form to appear as a dropdown list:

<%= form_tag job_index_path do %>
  <%= select_tag "area", options_for_select(@areas.collect { |area| [ area.name, area.name ] }), :onchange => "this.form.submit();" %>
<% end %>

The desired outcome is that when the form is submitted it will take the 'area' that the user select and add it as a params[:area] option for the following route:

get ':area' => 'job#index', :as => 'job_index'

For example, if the list that has three options: London, Dublin, Paris. When the user selects 'Dublin', the form submits and assigns params[:area] to be 'Dublin'. It then goes to the URL localhost:3000/Dublin.

However, I can't figure out how to add the :area parameter to the form path once the user makes their suggestion. I'm sure its probably a very easy thing to do, but I can't seem to figure it out.

Any help is greatly appreciated :)

samedi 17 décembre 2016

Rails 3: how to check if very large migration is running properly

I want to update all of a column in a table with over 2.2 million rows where the attribute is set to null. There is a Users table and a Posts table. Even though there is a column for num_posts in User, only about 70,000 users have that number populated; otherwise I have to query the db like so:

@num_posts = @user.posts.count

I need to use a migration to update the attributes and I'm not sure whether or not it's running properly. Here is my migration file:

class UpdateNilPostCountInUsers < ActiveRecord::Migration
  def up
    nil_count = User.select(:id).where("num_posts IS NULL")

    nil_count.each do |user|
      user.update_attribute :num_posts, user.posts.count
    end
  end

  def down
  end
end

In my console, I ran a query on the first 10 rows where num_posts was null, and then used puts for each user.posts.count . The total time was 85.3ms for 10 rows, for an avg of 8.53ms. 8.53ms*2.2million rows is about 5.25 hours, and that's without updating any attributes.

How do I know if my migration is running as expected? Is there a way to log to the console %complete? I really don't want to wait 5+ hours to find out it didn't do anything. Much appreciated.

vendredi 16 décembre 2016

Rails 3 HABTM yields ActiveRecord::Associations::CollectionProxy objects

I have a legacy Rails 3 application and I'm trying to set up a simple HABTM relationship between two models: VolunteerCircle and User. I have this same association in two other models.

The associations are as follows:

VolunteerCircle model:

class VolunteerCircle < ActiveRecord::Base 
    #...

    has_and_belongs_to_many   :users 

    # ...
end

User model:

class User < ActiveRecord::Base
  #...

  has_and_belongs_to_many :volunteer_circles

  #...
end

And here is the migration:

class CreateVolunteerCirclesUsers < ActiveRecord::Migration
  def change
    create_table :volunteer_circles_users, id: false do |t|
      t.belongs_to :volunteer_circle, index: true
      t.belongs_to :user, index: true
    end
  end
end

When I call #users on a VolunteerCircle object (or vice-versa), Rails coughs up an ActiveRecord::Associations::CollectionProxy object.

The volunteer_circles_users table looks right to me in the database. What am I missing here?

Also, I am aware of the superiority of HABTMT. Circumstances beyond my control dictate HABTM here.

Thank you so much!

Sinatra ajax file uploading: invalid byte sequence in UTF-8

The title might sound trivial, but it's not that easy.

I have a Rails 3 app has an API powered by Sinatra. What I'm trying to do is to upload a picture from my Insomnia REST client.

And here's the problem.

First, I send my picture as a file parameter.

Insomnia REST client interface

My entry point is this method:

app.post '/account/avatar', authorization: true do
  query('account/avatar').upload(params[:file])
end

But params[:file] content seems a bit weird.

0> params[:file]
=> "\xFF\xD8\xFF\xE0\u0000\u0010JFIF\u0000\u0001\u0001... (you got the point)

Most String methods fail with the following error:

0> params[:file].present?
=> invalid byte sequence in UTF-8

But I was expecting to see something like this:

params[:file] = {
  :filename=>"mock-up-1.jpg",
  :type=>"image/jpeg",
  :name=>"file",
  :tempfile=>#<Tempfile:/var/folders/dq/nylzy6q151nc7n4y5bj4b6y9pyqtgz/T/RackMultipart20140929-13931-1qucfg1>,
  :head=>"Content-Disposition: form-data; name=\"file\"; filename=\"foo.jpg\"\r\nContent-Type: image/jpeg\r\n"
}

My headers are:

Content-Type: multipart/form-data
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
X-File-Name: mock-up-1.jpg

How to get Condition Group in Ransack?

I am using advanced search in Ransack which has default AND. I have made it as OR by putting .try(:merge, m: 'or'))

@search = Data.search(params[:q].try(:merge, m: 'or'))

but I am not able to get the AND/OR drop down as Condition Group like shown in Ransack Demo here http://ift.tt/1PM7QsC

enter image description here

How to do it as unfortunately Ransack wiki has no mention about it.

jeudi 15 décembre 2016

Change the value of hash

I have a array of hash

response = [{"id"=>"008CFA1213EA1479500703798", "updated_at"=>"2016-11-18T20:27:03Z"}, {"id"=>"F452144578701479479453499", "updated_at"=>"2016-11-18T14:54:51Z"}] 

Desired Output

 desired_response = [{"id"=>"008CFA1213EA1479500703798", "updated_at"=>Fri, 18 Nov 2016 20:27:03 UTC +00:00}, {"id"=>"F452144578701479479453499", "updated_at"=>Fri, 18 Nov 2016 14:54:51 UTC +00:00}]

What I have do so far,

response.map {|x| x["updated_at"]}
["2016-11-18T20:27:03Z", "2016-11-18T14:54:51Z"]

response.map {|x| x["updated_at"]}.map {|x| DateTime.strptime(x).in_time_zone} 
[Fri, 18 Nov 2016 20:27:03 UTC +00:00, Fri, 18 Nov 2016 14:54:51 UTC +00:00]

I got the updated_at desired format but how to put it in response updated_at value or is there a better way to do this? Thanks

Rails: Cannot access column from a join-table in a partial

I want to access a column from a join-table in a partial. When I access this column in a "normal" view (e.g. fakeposts#index) it is working, however if I want to do the same in a partial, it does not work.

Example:

I have a users and a fakeposts table. For each user I want to display the fakeposts in a specific (randomized) order - namely based on a randomized_time column -, which is saved in a join table:

randomized_posts table:

user_id | fakepost_id | randomized_time

My Models look like this:

#user.rb
has_many :randomized_posts

#fakepost.rb
has_many :randomized_posts

# randomized_post.rb
belongs_to :fakepost
belongs_to :user

In my fakepost_controller.rb I want to get the fakeposts for the current_user and add the column "randomized_time" to my selection:

My fakepost_controller.rb

def index
  @fakeposts = Fakepost.joins(randomized_fakeposts).where(randomized_fakeposts: {user_id: current_user.id}).select("fakeposts.*, randomized_fakeposts.randomized_time")
end

This is working: index.html.erb

<% @fakeposts.each do |post| %>
   <%= post.randomized_time %>
<% end %>

This is not working: index.html.erb and my partial

#index.html.erb
<% @fakeposts.each do |post| %>
   <%= render :partial => "layouts/individual-post", :locals => {:post => post} %>
<% end %>

#layouts/_individual-post.html.erb
<%= post.randomized_time %>

However, something like <%= post.created_at %> is working fine in my partial so I guess calling my partial is correct?

Limit Ransack drop down options

I am using Ransack and it is working really well on our Data model. Now the issue is, in the dropdown, it shows us all the 15 option like id, name, age, gender, type, location, SSN, company, status etc.

I only want 3 options to be shown in the drop down say name, gender and location (all being text fields). How can I do it ?

data_controller.rb

@search = Data.search(params[:q].try(:merge, m: 'or'))
@datum = @search.result(:distinct=>true).paginate(page: params[:page], per_page: 30)

data.html.erb

    <div class="row">
        <div class="col-lg-10">
            <div class="form_search">
                <%= search_form_for @search, url: search_data_index_path, html: { method: :get, class: "data_search" } do |f| %>
                <%= f.condition_fields do |c| %>
                <%= render "condition_fields", f: c %>
                <% end %>
                <p><%= link_to_add_fields "Add Conditions", f, :condition %></p>
                <br>
                <div class="actions">
                    <%= f.submit "Search", :class => "btn btn-primary" %>
                </div>
                <% end %>
            </div>
        </div>
    </div>

Thanks

Company has_many users (Rails and Devise)

I have a problem. It turns out that I have 2 models, Users and Companies. I need every company to have its users, until then it's easy, Company:: has_many Users Througth users_company.

What I need is to get the company to invite users and when they log in to the company panel.

By the way also normal users are logged.

Is there any guide please?

Excuse my English, I speak Spanish.

Thank you.

RoR How to set the root to show the latest entry in a model

Have researched and seen alot of ways of retrieving the latest entry in a model using something like Post.order("created_at").last but have been unsuccessful in making that the root for the webpage to land on

mercredi 14 décembre 2016

An SMTP To address is required to send a message/Argument Errror

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

Good Day Guys,I am having trouble debugging this myself and have consumed so much time I needed your help and explanation as to how why it didn't work.

Things I did already: 1.Added gem 'binding_of_caller' 2.bundle install

goal: Is when a visitor submit a contact form it supposed to send me a email message automatically.

My woes/confusion:

1.How do you set your email in secrets.yml or put your email wherein you configured the contact form request directly to your email 2.What I did is put to:myemail.com > secrets.yml both in production and development 3.Am I right?

Please explain this to me as I am going in depth on ruby on rails.

Rails - Model with attributes, which are not stored in the database

The whole project is build like that: I've got an api which provides data and saves data. Than another Application which converts the data of the data api into "nice and clean" data. and than a frontend, which takes the nice and clean data.

In the Middle part, I got the Model Field. It has multiple Attributes like: id, area, etc. those attributes are also in the schema.rb. Now I also have attributes like: field_nr which are not in the schema.rb. But taken from the api, converted and then printed as json. Now I have to read from the field model the attribute field_nr, which is not in the schema.rb/database. How can I read those attributes?

Thanks for your help & just ask if something is unclear

A script to install everything from scracth

#!/bin/sh

## update & upgrade
sudo apt-get update
sudo apt-get upgrade

## install rvm with ruby & rails
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
\curl -sSL https://get.rvm.io | bash -s stable
\curl -sSL https://get.rvm.io | bash -s stable --ruby
rvm --default use ruby-2.3.1
gem update --system
source ~/.rvm/scripts/rvm

## rvm lib requirements
rvm requirements
rvmsudo /usr/bin/apt-get install build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion -y
rvm install ruby-2.3.1

## install passenger
gem install passenger

## install nginx with passenger and recompile it - default
 echo | rvmsudo passenger-install-nginx-module -y

## install curl ssl for passenger
sudo apt-get install libcurl4-openssl-dev -y

## define where to find nginx
wget -O init-deb.sh http://ift.tt/PfsLUk
sudo mv init-deb.sh /etc/init.d/nginx
sudo chmod +x /etc/init.d/nginx
sudo /usr/sbin/update-rc.d -f nginx defaults

## after that you can control nginx with
sudo /etc/init.d/nginx stop
sudo /etc/init.d/nginx start

## create directory for application
mkdir www
mkdir www/rails

## create new app
cd www/rails
rvm use ruby-2.3.1@myApp --ruby-version --create
gem install rails
rails new .


### ADD MANDATORY GEMS ###
## install postgreSQL with right packages
sudo apt-get install libpq-dev -y

rails g react:install

My goal is to make a script which will install :

- rvm to manage ruby & rails versions
- nginx and passenger ( not with apt-get i nginx )
- add postgresql
- create directory & app in /home/ubuntu/www/rails/myApp
- install react and assets
- modify if possible nginx conf to work with passenger ( no location {} and need passenger_enabled on )
- build connection if possible between the app and postgreSQL DB of RDS AWS
- start the server and is accessible

If someone got any suggestions for how to improve this script is welcomed :)

for now since last ruby version 2.3.1, it s seems that RVM stable is still 2.3.0 and when i force install 2.3.1 it remove rails unless i redo "gem install rails"

thanks for your help !