jeudi 31 décembre 2015

Error showing search results when using nested resource routes - Rails

Long time reader, first time poster! I keep receiving the below error message when trying to view the results of a search when using nested resource routes as below. For some reason I can't get rails to show the results of my search using the following routes and using the redirect_to @search call in the controller.

routes.rb:

resources :users do
    resources :searches
end

Below is the Error:

NoMethodError in SearchesController#create

undefined method `search_url' for #<SearchesController:0x007fc68a881708>

      Extracted source (around line #19):
17 @search = current_user.searches.create(search_params)
18
19  redirect_to @search
20
21 end
22

Searches Controller:

class SearchesController < ApplicationController
  before_action :require_user

  def index
  end

  def new
    # @states = ["red","green","blue"]
    @states = State.all
    @cities = City.all
    @languages = Language.all
    @search = Search.new
  end

  def create
    @search = current_user.searches.create(search_params)
    redirect_to @search
    #Old Search
    #@search = Search.create(search_params)
  end

  def show
    #@search = Search.find(params[:id])
    #@search = @user.searches.find(params[:id])
    @search = current_user.searches.find_by(id: params[:id])
  end

  #Deleting searches, tied to the "delete link" on the view
  def destroy
    @search.destroy
    flash[:success] = "Micropost deleted"
    redirect_to request.referrer || @searches
  end

  private

  def search_params
    #:userid = @user.id
    params.require(:search).permit(:searchname, :city, :min_gpa, :max_gpa, :firstname, :state, :city, :age, :gender, :universityname, :language, :livingin, :workexperience, :monthsspentabroadLiving, :monthsspentabroadworking, :degree , :degreetype, :countryofdegree, :wantstoworkin, :hasworkexperiencein, :permissiontoworkin, :currentlyemployed, :referencesuponrequest, :worktype, :charitywork)
  end
end

New Search Form - View:

 <%= bootstrap_form_for @search, url: user_searches_path(current_user), html: {class: "pure-form"} do |s| %>

          <%= s.hidden_field :userid, :value => current_user.id %>

          <div class="field">
            <%= s.text_field :searchname, label: "Search Name" %>
          </div>

Migration in rails

Let us say I have a initial migration which is created during the model generation

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps null: false
    end
  end
end

and sometimes later I want to add a field password in this migration like

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :password_digest

      t.timestamps null: false
    end
  end
end

without creating a migration file rails generate migration add_password_digest_to_users password_digest: string can I add t.string :password_digest field to the initial file and run rake db:migrate command.

Why do we need to create a migration file to add this, instead of just adding t.string :password_digest and run bundle exec rake:db migrate

Isn't it overwhelming to create a 20 migrations, when we required to add 20 fields to the initial migration for a single model.

Rails f.select saving integer not string

I have the following line in a rails form for a new submission:

<%= f.select :department_id, options_from_collection_for_select(@departments, 'id', 'department') %>

I am trying to have it save the department_id as a string, being the actual title of the respective department saved. Instead I am getting the integer value for the ID of the chosen department.

How to populate empty attributes with random values from seeds.rb

I've generated User model with attributes: first_name, last_name, city. Then, I've created 200 instances of the class using seed.rb and gem 'faker'. After all, I have added one more attribute to this model - age:string, so now in every instance of the class the age = 'nil'. Now, I want to populate every single user with randomly generated number from range 10..99. Here is my code from seed.rb:

users = User.all
users.each do |element|
    element.age = rand(10..99).to_s
end

When I type rake db:seed it seems to be successfull but when I check the database, each age:string is still 'nil'. Do you have any idea what might have gone wrong?

Rails 3 - delete_all doesn't support limit scope whereas MySQL supports it

I have a table with 9 millions of records. I was periodically syncing this data to a third party. I am keeping a column that tells if a particular row has already been deleted or not.

Now I need to delete almost 6 million synced rows and I am not sure if running

Model.where(:sync_flag => true).delete_all

would be a nice idea. There are hundreds of inserts per second and I think it might result in locking the table in a way that would hurt/block the inserts ( MySQL expert needed here to correct )

With the above prologue, I thought of using a delete with a limit clause in a loop to delete all the records until none left but with the following

Model.where(:sync_flag => true).limit(5000).delete_all

it raised an exception delete_all doesn't support limit scope.

Is there a workaround to deal with the issue without leaving the Rails environment ?

mercredi 30 décembre 2015

Как корректно получить данные Ruby on Rails для Chertkick?

Есть модели:

uk.rb

class Uk < ActiveRecord::Base
    has_many :oplata
end

oplata.rb

class Oplata < ActiveRecord::Base
    belongs_to :finperod
    belongs_to :uks
end

И миграции:

class CreateUks < ActiveRecord::Migration
  def change
    create_table :uks do |t|
      t.integer :uk_id
      t.string :meaning

      t.timestamps
    end
  end
end


class CreateOplata < ActiveRecord::Migration
  def change
    create_table :oplata do |t|
      t.integer :finp_id
      t.integer :np_id
      t.integer :uk_id
      t.integer :saldo
      t.integer :oplata

      t.timestamps
    end
  end
end

*htm.erb Для Chartkick пишу

<%= pie_chart Oplata.sum(:oplata, :group => "uk_id")%>

Получаю график из хэша:

  new Chartkick.PieChart("chart-1", {"100":448616,"102":224308,"101":112154}, {});

Как я могу заменить ключи в этом хэши на значения MEANING из таблицы UKs?

Пробовал использовать

 <%= pie_chart Uk.find_by_sql("SELECT uks.MEANING, SUM(OPLATA) FROM oplata o, uks WHERE o.UK_ID = uks.UK_ID GROUP BY uks.MEANING")

График не отображается, так как передаются следующие данные:

  new Chartkick.PieChart("chart-1", [{"meaning":"Имя 1","sum(oplata)":448616,"id":null},{"meaning":"Имя 2","sum(oplata)":112154,"id":null},{"meaning":"Имя 3","sum(oplata)":224308,"id":null}], {});

wrong number arguments (0 for 1) (ArgumentError)

Looks like rspec is not passing any arguments to the method, even though they're written in the spec file.

The method:

def echo(msg)
  msg
end

The test:

require './echo.rb'

describe echo do
  it 'echoes' do
    expect(echo('hello')).to eq('hello')
  end
end

terminal output:

/home/.../scratch/echo.rb:1:in `echo': wrong number of arguments (0 for 1) (ArgumentError)
from /home/.../scratch/scratch_spec.rb:3:in '<top (required)>'
from /home/.../.rvm/gems/ruby-2.2.1/gems/rspec-core-3.4.1/lib/rspec/core/configuration.rb:1361:in 'load'
...

How to add http link on image tag using rails?

I am using ruby 2 and rails 4. I want to add http link into image link in rails. How can I create that?

My codes:

<% for g in @pictures %>                              
   <%= link_to image_tag g.pic_url, class: "img-responsive img-thumbnail" %> 
<% end %> 

I want to create something like below using rails.

<a href="/assets/image_001.jpg"><img src="/assets/image_001.jpg" class="img-responsive img-thumbnail"></a>

Please share with me if any one has any idea.

Create a claim form for devise on rails by replicating the forget password form

I have a system in place where people need to claim accounts already set in a database by proving that they own the same email address. Every user in the user database has a password generated by Devise using the friendly token, so that people can still just login via omniauth plugins.

The current method I have planned out is to create a separate version of password#new (from Devise) as the 'claim' form, but I'm not too sure where to go from there. Do I have to create a whole new model? or can I just create a PasswordsController and config routes to go to a new view?

I18n.t Translation Missing Default Value Nil

So I know how return a default value if I get "translation missing:" when reading a yaml file.

some = I18n.t("something.something_else", default: "value")

But how do I do that in the Ruby way if I want the default value to be nil? I know I can regex and match for "translation missing:" from the variable some and if it matches, I would have it assign to nil. But what I wanted to do is have

some = I18n.t("something.something_else", default: nil)

But it just returned translation missing for me. Does anyone know a good way?

rails unit testing with ActiveRecord associasions without hitting the DB

TL;DR I'd like to know if I can test model methods that use querying (i.e find, where) without persisting test objects to the database.

So I'm new to rails, and working on an existing codebase.
One thing I've noticed is that our unit tests take forever to run.
Upon investigation, the culprit was, of course, that we persist everything to DB when we test our models.
So, I set out to try and write model tests that don't hit the DB, but I've come across a snag:
When a model has an association with other models, any operations that are performed on it assume that everything is persisted.

Let's take a look at an example-

class Parent < ActiveRecord::Base
  has_many :children, dependent: :destroy

  def default_child
    children.find_by(default: true)
  end

end

So naturally I want to test that my default_child method is working:

parent = Parent.new
default_child = parent.children.build(default: true)

assert_equal default_child, parent.default_child

but this test fails, because the actual result of parent.default_child is nil!
This is because internally, the default_child method uses find_by, which, it seems, only works in the context of persisted objects.

So I'm forced to write the test like so-

parent = Parent.new
# I don't want to do this!!
parent.save
# why 'create' and not 'build'?
default_child = parent.children.create(default: true)

assert_equal default_child, parent.default_child

Which is uglier and slower.
Is there any way I can test these operations in memory?

I've tried setting children manually (parent.children = [ child1, child2 ]).
This does not cause an error, but it seems that find_by doesn't look there, but rather in the DB...

I see that a similar question came up 3 years ago, without a conclusive answer, I'm wondering if anything's changed since then..

P.S. bonus question- what can I do about validations which are on: update? seems like I have to persist the test object at least once before they are invoked..

mardi 29 décembre 2015

Rails has_many through intermediate model

In rails, is there a way to fetch transitive models. We have following model structure.

A customer has many purchases and a purchase has many orders. There is no direct relation between customer and order model. They can be linked through purchase model. Now I want to fetch all orders belongs to a customer. Is there a way of achieving this through a single query. Our current models look something like.

Customer
    - customer_id

Purchase
    - purchase_id
    - customer_id

Order
    - order_id
    - purchase_id
    - status

My usecase is to given a customer object, list all orders of a customer which are in a specific state (e.g status = 'Complete').

Row SQL would look something like

SELECT purchase_id, order_id FROM Customer c INNER JOIN Purchase p ON p.customer_id = c.customer_id INNER JOIN Order o ON o.purchase_id = p.purchase_id WHERE o.status = 'Complete';

Circular dependency error in will_paginate when try install geocode geolite database rails

I get error in: rails 4.1 ruby 2.1 will_paginate 3.0 activerecord 4.2

Any idea? Thanks!

rake geocoder:maxmind:geolite:load PACKAGE=city
File already exists (GeoLiteCity_20151201/GeoLiteCity-Blocks.csv), skipping
File already exists (GeoLiteCity_20151201/GeoLiteCity-Location.csv), skipping
Resetting table maxmind_geolite_city_blocks...rake aborted!
Circular dependency detected while autoloading constant ActiveRecord
/***lib/will_paginate/active_record.rb:247:in `<module:ActiveRecord>'
/***lib/will_paginate/active_record.rb:23:in `<module:WillPaginate>'
/***lib/will_paginate/active_record.rb:11:in `<top (required)>'
/var/lib/gems/2.1.0/gems/geocoder-1.2.11/lib/maxmind_database.rb:26:in `block in insert'
/var/lib/gems/2.1.0/gems/geocoder-1.2.11/lib/maxmind_database.rb:24:in `each'
/var/lib/gems/2.1.0/gems/geocoder-1.2.11/lib/maxmind_database.rb:24:in `insert'
/var/lib/gems/2.1.0/gems/geocoder-1.2.11/lib/tasks/maxmind.rake:71:in `insert!'
/var/lib/gems/2.1.0/gems/geocoder-1.2.11/lib/tasks/maxmind.rake:25:in `block (4 levels) in <top (required)>'
Tasks: TOP => geocoder:maxmind:geolite:load => geocoder:maxmind:geolite:insert

Rails and sucker_punch: Wait for high frequency updates to complete before running background job on that model

In my Rails 3.2 project, I am using SuckerPunch to run a expensive background task when a model is created/updated.

Users can do different types of interactions on this model. Most of the times these updates are pretty well spaced out, however for some other actions like re-ordering, bulk-updates etc, those POST requests can come in very frequently, and that's when it overwhelms the server.

My question is, what would be the most elegant/smart strategy to start the background job when first update happens, but wait for say 10 seconds to make sure no more updates are coming in to that Model (Table, not a row) and then execute the job. So effectively throttling without queuing.

My sucker_punch worker looks something like this:

class StaticMapWorker
    include SuckerPunch::Job
    workers 10

    def perform(map,markers)
        #perform some expensive job
    end
end

It gets called from Marker and 'Map' model and sometimes from controllers (for update_all cases)like so:

after_save :generate_static_map_html

def generate_static_map_html
    StaticMapWorker.new.async.perform(self.map, self.map.markers)
end

So, a pretty standard setup for running background job. How do I make the job wait or not schedule until there are no updates for x seconds on my Model (or Table)

If it helps, Map has_many Markers so triggering the job with logic that when any marker associations of a map update would be alright too.

Rails has_many sums and counts with ActiveRecord

I've got a dilemma I think I may have coded myself into a corner over. Here's the setup.

My site has users. Each user has a collection of stories that they post. And each story has a collection of comments from other users.

I want to display on the User's page, a count of the total number of comments from other users.

So a User has_many Stories, and a Story has_many comments.

What I tried was loading all the users stories in @stories and then displaying @stories.comments.count, but I get undefined method 'comments' when I try to do that. Is there an efficient ActiveRecord way to do this?

Traverse through a certain month in Date with just a given integer

Would it be possible to go to a certain month of the year with just a given integer. For example

date = Date.today
=> Wed, 30 Dec 2015

What if I want to go back to a certain month based on that date and I am just given a number let's say 7 which is July in the Date::MONTHNAMES so would it be possible to do something like

date = Date.today
=> Wed, 30 Dec 2015
date.go_to_month_of(7) # which will bring me back to July 30, 2015

Turbolink events don't trigger for pages inside Rails engine

I'm building a platform that gives users a variety of therapeutic tools toward treating anxiety and depression. The 'main app' has some JS with a Turbolink page:change event—everything works swell and the page:change event fires on page changes. For demonstration purposes, this block of code triggers both alerts when navigating throughout 'main app.'

$( document ).ready(function() {
  alert("DOM fully loaded and parsed!");
    $(document).on("page:change", function() {
        alert("Page changed detected!");
    });
});

I have a Rails engine that plugs into the main app. In the engine's JS manifest file, I'm pulling in the main app's JS file like so:

Engine's Application.js:

//= require turbolinks
//= require jquery
//= require jquery_ujs
//= require main_app/custom

The problem is that the Turbolinks on:change event is not triggering when navigating the engine pages (the 'DOM fully loaded...' alert appears as expected). The Chrome debugging console shows no errors, so I'm lead to believe Turbolinks is loaded when viewing engine pages.

tlrd: Turbolinks page:change events works great in the main app, do not fire at all in engine.

Any input is appreciated.

Rails paperclip rename a style

I'm trying to rename a Paperclip style in my Rails app, already in production. I want to rename style "mini" as "small". Is enough changing just in the model?

has_attached_file :photo,
  :styles => {
    :mini => "60x60",
    :medium => "200x200>",
    :large => "300x300"}

Thanks!

rails model attribute ensure uniqueness except for certain value

In rails, I could restrict certain attribute to be unique within scope but pass on nil or blank. How could I ensure uniqueness but pass on certain value?

I encrypted an attribute, so it's not nil anymore. But I do allow nil for this attribute in the model.

how to convert bytes into mbs,gbs

I am trying to convert number of bytes into kilobytes,megabytes.i have generated a table in which all files are getting with name and filesize.but the filesize is in bytes, I just want to convert long length of numbers into mbs,gbs. this is show file's code:

  for file in files[1]
            if file[1][:size] == nil
                filesize = 0
            else
                filesize = file[1][:size]
            end
            data += [["#{file[1][:name]}", "#{filesize.to_s(:human_size)} Bytes"]]
        end

In which i have used .to_s(:humansize) function due to which this error is encountered

    can't convert Symbol into Integer 

thanks!

How to setup delayed jobs with multi schema based application Rails.?

Can you guys guide how I will allow rake jons:work to work for the multiple schema in both development and production environment. Thanks in advance.

lundi 28 décembre 2015

How to migrate a rails 3 app to rails 4

How to migrate a rails 3 app to rails 4 (including migration from ruby 2.0.0 to 2.2.x)

Are there any tools/libraries which will help us to isolate code + queries which needs migration.

Activeadmin, duplicating has_many records

When I use ActiveAdmin to edit one Agency, I can select a City and associates it to the Agency. The city is linked to the Agency, but the city is all the times duplicated in the database.

My models:

# agency.rb
class Agency < ActiveRecord::Base
  has_many :agency_cities
  has_many :cities, through: :agency_cities
  accepts_nested_attributes_for :cities, allow_destroy: true
end

# city.rb
class City < ActiveRecord::Base
  has_many :agency_cities
  has_many :agencies, through: :agency_cities
end

# AgencyCity.rb
class AgencyCity < ActiveRecord::Base
  belongs_to :agency
  belongs_to :city
end

I read the doc of Activeadmin and added the [:id] permit_parameter, but I still have the problem, I'm very confused.

# admin/agency.rb
ActiveAdmin.register Agency do
  permit_params :name, :picture,
    cities_attributes: [:id, :name, :description, :_destroy]

  form do |f|
     f.inputs "Agencies" do
       f.input :picture, as: :file
       f.input :creation_date, label: 'Creation Date'
       f.input :name, label: 'Name'
     end
   end

   f.inputs do
     f.has_many :cities do |k|
       k.input :name, label: 'City',
         as: :select,
         collection: City.all.map{ |u| "#{u.name}"}
       k.input :_destroy, as: :boolean
     end
   end
   f.actions
end

Connecting SendGrid with Heroku

I have created a new Action Mailer that will allow me to be notified by email when someone clicks on the "Click to Connect" button. I'm following a tutorial and was able to successfully set up the connection with SendGrid on Heroku from my "contact us" button. Currently when I click the button it opens my computer's email app instead of triggering the SendGrip app.

users/show.html.erb

<div class='container'>
<div class='row'>
    <div class='col-md-3 text-center'>
        <%= image_tag @user.profile.avatar.url, class: 'user-show-avatar' %>
    </div>
    <div class='col-md-6'>
        <h1><%= @user.profile.first_name %></h1>
        <h3><%= @user.profile.city %>, <%= @user.profile.state %>, <%= @user.profile.country %></h3>
        <div class='well profile-block profile-description'>
            <h4>Bio</h4>
            <p><%= @user.profile.bio %></p>
            <h4>Coding Languages</h4>
            <p><%= @user.profile.coding_languages %></p>
            <h4>Mentoring Needs</h4>
            <p><%= @user.profile.mentoring_needs %></p>
        </div class='connect_button'>
        <a class="btn btn-primary btn-lg btn-block active" href="mailto:connections@jrdevmentoring.com" role="button">Click to Connect</a>
    </div>
</div>

mailers/connection_mailer.rb

class ConnectionsMailer < ActionMailer::Base
    default to: 'connections@jrdevmentoring.com'

    def connection_email(name, email, body)
        @name = name
        @email = email
        @body = body
        mail(from: email, subject: 'Jr. Dev Mentoring Connect Form Message')
    end
end

config/environment.rb

# Load the Rails application.
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
Rails.application.initialize!

ActionMailer::Base.smtp_settings = {
  :address => 'smtp.sendgrid.net',
  :port => '587',
  :authentication => :plain,
  :user_name => ENV['SENDGRID_USERNAME'],
  :password => ENV['SENDGRID_PASSWORD'],
  :domain => 'heroku.com',
  :enable_startstls_auto => true
}

How to access user table data based on friends table

I am new for ruby on rails, i am trying to access User Details based on the User_id in the Friends Table.

ChatController:

class ChatController < ApplicationController
    def dashboard
        @avatar = Profilephoto.find_all_by_user_id(session[:userid])
        frnds_list_with_status_and_msg_count
    end

    def frnds_list_with_status_and_msg_count
        @id = session[:userid]
        #getting list of friends having for the current user
        @frnds = Friend.find_all_by_user_id(@id)
    end

    def getmessage      
    end     
end

models/User.rb

class User < ActiveRecord::Base
    has_and_belongs_to_many :friends 
end

models/friend.rb

class Friend < ActiveRecord::Base
    belongs_to :users
end

Here the problem i am facing is:

I am trying to access user friends from friends table and details from user table.

users table(id, name, paswd, nickname, fname, lname, status)

frieds table(id, user_id, friend_id)

Circular dependency detected while autoloading constant ConnectionsController

I am trying to add a new Action Mailer to my app and when I navigated to connections/new I received this error message:

Circular dependency detected while autoloading constant ConnectionsController

full trace

activesupport (4.1.0) lib/active_support/dependencies.rb:478:in `load_missing_constant'

activesupport (4.1.0) lib/active_support/dependencies.rb:180:in const_missing' activesupport (4.1.0) lib/active_support/inflector/methods.rb:238:inconst_get' activesupport (4.1.0) lib/active_support/inflector/methods.rb:238:in block in constantize' activesupport (4.1.0) lib/active_support/inflector/methods.rb:236:ineach' activesupport (4.1.0) lib/active_support/inflector/methods.rb:236:in inject' activesupport (4.1.0) lib/active_support/inflector/methods.rb:236:inconstantize' activesupport (4.1.0) lib/active_support/dependencies.rb:552:in get' activesupport (4.1.0) lib/active_support/dependencies.rb:583:inconstantize' actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:76:in controller_reference' actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:66:incontroller' actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:44:in call' actionpack (4.1.0) lib/action_dispatch/journey/router.rb:71:inblock in call' actionpack (4.1.0) lib/action_dispatch/journey/router.rb:59:in each' actionpack (4.1.0) lib/action_dispatch/journey/router.rb:59:incall' actionpack (4.1.0) lib/action_dispatch/routing/route_set.rb:676:in call' warden (1.2.4) lib/warden/manager.rb:35:inblock in call' warden (1.2.4) lib/warden/manager.rb:34:in catch' warden (1.2.4) lib/warden/manager.rb:34:incall' rack (1.5.5) lib/rack/etag.rb:23:in call' rack (1.5.5) lib/rack/conditionalget.rb:25:incall' rack (1.5.5) lib/rack/head.rb:11:in call' actionpack (4.1.0) lib/action_dispatch/middleware/params_parser.rb:27:incall' actionpack (4.1.0) lib/action_dispatch/middleware/flash.rb:254:in call' rack (1.5.5) lib/rack/session/abstract/id.rb:225:incontext' rack (1.5.5) lib/rack/session/abstract/id.rb:220:in call' actionpack (4.1.0) lib/action_dispatch/middleware/cookies.rb:560:incall' activerecord (4.1.0) lib/active_record/query_cache.rb:36:in call' activerecord (4.1.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:621:incall' activerecord (4.1.0) lib/active_record/migration.rb:380:in call' actionpack (4.1.0) lib/action_dispatch/middleware/callbacks.rb:29:inblock in call' activesupport (4.1.0) lib/active_support/callbacks.rb:82:in run_callbacks' actionpack (4.1.0) lib/action_dispatch/middleware/callbacks.rb:27:incall' actionpack (4.1.0) lib/action_dispatch/middleware/reloader.rb:73:in call' actionpack (4.1.0) lib/action_dispatch/middleware/remote_ip.rb:76:incall' rollbar (2.4.0) lib/rollbar/middleware/rails/rollbar.rb:24:in block in call' rollbar (2.4.0) lib/rollbar.rb:842:inscoped' rollbar (2.4.0) lib/rollbar/middleware/rails/rollbar.rb:22:in call' actionpack (4.1.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:incall' rollbar (2.4.0) lib/rollbar/middleware/rails/show_exceptions.rb:22:in call_with_rollbar' actionpack (4.1.0) lib/action_dispatch/middleware/show_exceptions.rb:30:incall' railties (4.1.0) lib/rails/rack/logger.rb:38:in call_app' railties (4.1.0) lib/rails/rack/logger.rb:20:inblock in call' activesupport (4.1.0) lib/active_support/tagged_logging.rb:68:in block in tagged' activesupport (4.1.0) lib/active_support/tagged_logging.rb:26:intagged' activesupport (4.1.0) lib/active_support/tagged_logging.rb:68:in tagged' railties (4.1.0) lib/rails/rack/logger.rb:20:incall' actionpack (4.1.0) lib/action_dispatch/middleware/request_id.rb:21:in call' rack (1.5.5) lib/rack/methodoverride.rb:21:incall' rack (1.5.5) lib/rack/runtime.rb:17:in call' activesupport (4.1.0) lib/active_support/cache/strategy/local_cache_middleware.rb:26:incall' rack (1.5.5) lib/rack/lock.rb:17:in call' actionpack (4.1.0) lib/action_dispatch/middleware/static.rb:64:incall' rack (1.5.5) lib/rack/sendfile.rb:112:in call' railties (4.1.0) lib/rails/engine.rb:514:incall' railties (4.1.0) lib/rails/application.rb:144:in call' rack (1.5.5) lib/rack/lock.rb:17:incall' rack (1.5.5) lib/rack/content_length.rb:14:in call' rack (1.5.5) lib/rack/handler/webrick.rb:60:inservice' /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:138:in service' /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:94:inrun' /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'

controllers/connections_controller.rb

class ConnectionionsController < ApplicationController
  def new
    @connection = connection.new
  end

  def create
    @connection = Connection.new(connection_params)
    if @connection.save
      name = params[:connection][:your_name]
      email = params[:connection][:email]
      body = params[:connection][:mentors_name, :mentees_name]

      connectionMailer.connection_email(name, email, body).deliver
      flash[:success] = "Message sent. Someone at Jr. Dev Mentoring will respond to your message soon. Thank you."
      redirect_to new_connection_path
    else
      flash[:danger] = "Error occured, message has not been sent. You must complete all form fields"
      redirect_to new_connection_path
    end
  end
  private
    def connection_params
      params.require(:connection).permit(:your_name, :email, :mentors_name, :mentees_name)
    end
end

mailers/connection_mailer.rb

class ConnectionsMailer < ActionMailer::Base
    default to: 'info@jrdevmentoring.com'

    def connection_email(name, email, body)
        @name = name
        @email = email
        @body = body
        mail(from: email, subject: 'Jr. Dev Mentoring Connect Form Message')
    end
end

models/connection.rb

class Connection < ActiveRecord::Base
  validates :your_name, presence: true
  validates :email, presence: true
end

views/connections/new.html.erb

<div class="row">
  <div class="col-md-4 col-md-offset-4">
    <h1 class="text-center">Let's Connect</h1>
      <p class="text-center">I'd like to connect</p> 
      <div class="well">
        <%= form_for @connection do |f| %>
          <div class="form-group">
            <%= f.label :your_name %>
            <%= f.text_field :your_name, class: 'form-control' %>
          </div>
          <div class="form-group">
            <%= f.label :email %>
            <%= f.email_field :email, class: 'form-control' %>
          </div>
          <div class="form-group, 'Mentors Name'">
            <%= f.label :comments %>
            <%= f.text_area :mentors_name, class: 'form-control' %>
          </div>
          <div class="form-group, 'Mentees Name'">
            <%= f.label :comments %>
            <%= f.text_area :mentees_name, class: 'form-control' %>
          </div>

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

views/connection_mailer/connection_email.html.erb

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <p>You have received a message from the Jr. Dev Mentoring site's connect form, from <%= "#{ @name }, #{ @email }." %></p>
    <p><%= @body %></p>
  </body>
</html>

db/migrate

class CreateConnections < ActiveRecord::Migration
  def change
    create_table :connections do |t|
      t.string :your_name
      t.string :email
      t.text :mentors_name
      t.text :mentees_name

      t.timestamps
    end

schema

 create_table "connections", force: true do |t|
    t.string   "your_name"
    t.string   "email"
    t.text     "mentors_name"
    t.text     "mentees_name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

routes

Rails.application.routes.draw do
  devise_for :users,:controllers => { :registrations => "users/registrations" }
  resources :users do
    resource :profile
  end
  resources :connections
  resources :contacts
  get '/about' => 'pages#about'
  namespace :mentee do
    root 'pages#home'
    get '/mentor_profiles' => 'profiles#mentor_profiles'
  end
  namespace :mentor do
    root 'pages#home'
    get '/mentee_profiles' => 'profiles#mentee_profiles'
  end
  root 'pages#home'

Retrieve data from User table based on the id from Friends Table

I am having 2 tables Users and Friends.

Users Table fields(id,username, password, fname, lname, nickname,etc.,)

Friends Table fields(id, user_id, friend_id)

Now problem is i am trying to access user data based on friends table friends_id.

mysql query is :

SELECT *
FROM Users
inner JOIN Friends
ON Users.ID=Friends.Friend_ID;

but need only user data.

dimanche 27 décembre 2015

Devise: Remove confirmation email

I am using ng-token-auth with devise-token-auth.

This is my user.rb

class User < ActiveRecord::Base
  devise :database_authenticatable, :recoverable,
         :validatable, :omniauthable

  include DeviseTokenAuth::Concerns::User
end

I don't have confirmable listed but everytime I try to register, it tries to send a confirmation email and when I try to login, it says I have to follow the instructions in the email. How can I remove this? I went through the documentation and some posts, I thought that only happens when I have :confirmable in the user.rb. Any help would be appreciated. Thanks!

How to get spree product properties and spree properties for spree gem based application?

I am using spree gem. I am trying to get spree properties and spree product properties. But I got error

undefined local variable or method "prpty" for #<Class:0x007fa32588b128>

for CSV file in product. Where am I doing wrong?

 Spree::Product.class_eval do

    def self.to_csv
      CSV.generate do |csv|  
           all.each do |pro|
           csv << [ "property_name", "property_presentation", "property_value" ]
           var = Spree::Variant.find_by(product_id: pro.id)
           pro_prpty = Spree::ProductProperty.find_by(product_id: pro.id)
           prpty = Spree::Property.where(:id => pro_prpty.property_id)
           csv << [  pro_prpty.name, pro_prpty.value, pro_prpty.presentation,
           end
      end
     end
 end

column "pg_search_***" must appear in the GROUP BY clause or be used in an aggregate function

Tool.select('tools.id, tools.name').search('f')

the above query works fine but

Tool.select('tools.id, tools.name').group('tools.id').search('f')

produces the error

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "pg_search_3aaef8932e30f4464f664f.pg_search_469c73b9b63bebacc2607f" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...xt, '')), 'D') || to_tsvector('english', coalesce(pg_search_... I am using pg_search(http://ift.tt/1qZTg4u) gem for full text search..

I am not able to figure out the reason even tried adding

group("tools.id, tools.*, #{PgSearch::Configuration.alias('tools')}.rank")

as mentioned in the read me but still same error.

What is the proper way to frame the query? tq

Rails docx gem zip error

I am trying to use docx gem to use .docx file in my seed and docx-html gem to convert its content to html to display on page easilly. But I am having some troubles creating a Docx::Document object for my docx file.
seeds.rb


...
    d = Docx::Document.open('app/assets/seed/seed2.docx')
    d.to_html
...


And thats the error I get evry time i try to run rake db:seed

Zip::ZipError: Zip end of central directory signature not found

Do any of You have solution to this problem?

samedi 26 décembre 2015

Rails seeding db from docx files

I have to make an dictionary-like web app for my university organization and I ran into some problems. They sent me Terms for dictionary in .docx files and I am not sure how to insert them into Term model in my app. Docx. files looks something like this: enter image description here

Is there a possibility do easilly do It?
My Term model has phrase:string and explanation:text attributes.


This is my seed.rb file:

f = File.open(File.join(Rails.root, "/app/assets/seed/seed2.docx"))
while !f.eof do
  phrase = ''
  explanation = ''
  f.each_char do |c|
    if c == "–" #Separating Terms from its explanations.
      break
    end
    phrase << c
  end
  phrase[-1] = '' #delete ' '(space) from the end.
  f.each_line do |l|
    if l.to_s.strip.length == 0 # Check if new-line
      break
    end
    explanation << l
  end
  explanation[0] = '' #delete ' '(space) from the start.
  Term.create!(phrase: phrase, explanation: explanation)
end
f.close

I managed to seed files with pure text and display it using

<%= term.phrase %> -
<%= simple_format(term.explanation) %>

but I don't know how to import the tables and if is there a possibility to display the dotted lists from docx files? Please help, I feel like it is too big of a deal for me and I am not sure I can manage to implement such dictionary seeding from docx. I will appreaciate any help!

Order objects after duplicating/Deep cloning them Rails 4

I have a feature which copies the exiting object . The objects have multiple level of nesting . I am using deep_clone to achieve this .

Here is my controller code :-

@costing = @old_costing.deep_clone :include => [{:style => :images}, {:raw_materials => :costing_items}, :other_cost_fixeds, :other_costs, :exchange_rates ], :use_dictionary => true do |original, kopy|
                kopy.remote_picture_url = original.picture_url if kopy.is_a?(Image)

This redirects the request to a pre filled (with old costing) new view

In view I am doing this

<%= f.fields_for :other_cost_fixeds, f.object.other_cost_fixeds.order(:created_at => 'asc') , :validate => true do |fixed_cost| %>

The whole object disappears after doing this . I think this might be happening because the new object has not been created yet ? but if that is the case then how to order it ?

This is the object detail :-

- !ruby/object:RawMaterial
  raw_attributes:
    costing_id: 
    id: 
    name: Jam Button 9 mm Antique Silver
    rate: '1'
    raw_material_wastage: '0'
    total_raw_material: '8'
    slug: 
    created_at: 
    updated_at: 
    inventory_item_id: '758'
    costing_wastage: '0'
    pick_from_order_sheet: f
  attributes: !ruby/object:ActiveRecord::AttributeSet
    attributes: !ruby/object:ActiveRecord::LazyAttributeHash
      types: &6
        id: &3 !ruby/object:ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Integer
          precision: 
          scale: 
          limit: 
          range: !ruby/range
            begin: -2147483648
            end: 2147483648
            excl: true
        name: &2 !ruby/object:ActiveRecord::Type::String
          precision: 
          scale: 
          limit: 255
        rate: &1 !ruby/object:ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Float
          precision: 
          scale: 
          limit: 
        raw_material_wastage: *1
        total_raw_material: *1
        slug: *2
        costing_id: *3
        created_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: &4 !ruby/object:ActiveRecord::ConnectionAdapters::PostgreSQL::OID::DateTime
            precision: 
            scale: 
            limit: 
        updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: *4
        inventory_item_id: *3
        costing_wastage: *1
        pick_from_order_sheet: &5 !ruby/object:ActiveRecord::Type::Boolean
          precision: 
          scale: 
          limit: 
      values:
        id: '70'
        name: Jam Button 9 mm Antique Silver
        rate: '1'
        raw_material_wastage: '0'
        total_raw_material: '8'
        slug: 
        costing_id: '34'
        created_at: '2015-06-10 09:12:13.721016'
        updated_at: '2015-06-10 09:12:14.075739'
        inventory_item_id: '758'
        costing_wastage: '0'
        pick_from_order_sheet: f
      additional_types: &7 {}
      materialized: true
      delegate_hash:
        costing_id: !ruby/object:ActiveRecord::Attribute::FromUser
          name: costing_id
          value_before_type_cast: 
          type: *3
          value: 
        id: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: id
          value_before_type_cast: 
          type: *3
          value: 
        name: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: name
          value_before_type_cast: Jam Button 9 mm Antique Silver
          type: *2
          value: Jam Button 9 mm Antique Silver
        rate: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: rate
          value_before_type_cast: '1'
          type: *1
          value: 1.0
        raw_material_wastage: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: raw_material_wastage
          value_before_type_cast: '0'
          type: *1
          value: 0.0
        total_raw_material: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: total_raw_material
          value_before_type_cast: '8'
          type: *1
          value: 8.0
        slug: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: slug
          value_before_type_cast: 
          type: *2
          value: 
        created_at: !ruby/object:ActiveRecord::Attribute::FromUser
          name: created_at
          value_before_type_cast: 
          type: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
            subtype: *4
          value: 
        updated_at: !ruby/object:ActiveRecord::Attribute::FromUser
          name: updated_at
          value_before_type_cast: 
          type: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
            subtype: *4
          value: 
        inventory_item_id: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: inventory_item_id
          value_before_type_cast: '758'
          type: *3
          value: 758
        costing_wastage: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: costing_wastage
          value_before_type_cast: '0'
          type: *1
          value: 0.0
        pick_from_order_sheet: !ruby/object:ActiveRecord::Attribute::FromDatabase
          name: pick_from_order_sheet
          value_before_type_cast: f
          type: *5
          value: false
  new_record: true

As it can be seen the created_at value is appearing later and the created_at of the new_object is obviously empty, how do I access the created_at value which is appearing ?

How to prevent creating the instance of the class with specific IDs

I have 2 Models: Post, User. The User cannot like his post, so how can i prevent creating the instance of the Model Like (user_id: creator, post_id:created by the "creator") ?

vendredi 25 décembre 2015

ActiveRecord::RecordNotFound in RelationshipsController#destroy

Hi i am try to build an twitter like sample app .i have created a Relationship model ,In my view i have two forms one with follow button and another one with unfollow button in my view it looks like .

<% if current_user.following?(@otheruser) %>
     <%= render 'unfollow' %>
<% else %>
     <%= render 'follow' %>
 <% end %>

and i have in _follow.html.erb like

<%= form_for(current_user.active_relationships.build) do |f| %>
  <div><%= hidden_field_tag :followed_id, @otheruser.id %></div>
  <%= f.submit "Follow", class: "btn btn-primary" %>
<% end %>

and in _unfollow.html.erb like

<%= form_for(current_user.active_relationships.find_by(followed_id: @otheruser.id),
             html: { method: :delete }) do |f| %>
  <%= f.submit "Unfollow", class: "btn btn-danger" %>
<% end %>

in my user.rb i have methods and associations like

has_many :active_relationships,  class_name:  "Relationship",
                                   foreign_key: "follower_id",
                                   dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
  has_many :following, through: :active_relationships,  source: :followed
  has_many :followers, through: :passive_relationships, source: :follower   

  def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
  end

# Unfollows a user.

def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
  end

whenever i am clicking follow button it is creating a entry in relationship model in relationship.rb

class Relationship < ActiveRecord::Base
    belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
  validates :follower_id, presence: true
  validates :followed_id, presence: true
end

but when i am clicking on unfollow button it is giving error as "Couldn't find Relationship with 'id'=" and can anyone help me to know how i can display user.followers and user.following thing.

Where do I put my class files which are neither model, view nor controller?

I have a rails application. For one of my models, I created a specific class which will probably never be used anywhere else than in this specific model.

Where should I place the file corresponding to this class and its corresponding test file?

I currently placed it in /lib but since it will never be used elsewhere, I don't think that this is the right place for it.

Rail Application having blogs with comments

i am learning Ruby on Rails and i am using Rails 4. Following a Rails tutorial on Making a Blog App with Comments, the author wrote this to create a comment in comments_controller.rb

def create
@post=Post.find(params[:post_id])
@comment=@post.comments.build(params[:post].permit[:body])
redirect_to @post_path(@post)
end

and in the partial : _form.html.erb

<%= form_for([@post, @post.comments.build]) do |f| %>
<h1><%= f.label :body %></h1><br />
<%= f.text_area :body %><br />
<%= f.submit %>
<% end %>

I was wondering if i could only let the current user to comment on a post, having made all appropriate associations between User Model and Comment Model, so that while displaying the comments, i could retreive information from the User through Comment. Clearly, i do not just want to use a

before_action :authenticate_user!

as i want an association between User and Comment.

how to concatenate in Rails ERB a sstring like this in img_tag?

I need something like this:

<%= image_tag "/center_images/#{center.image}" %>

I have test a lot of things but there is no way.

Any idea?

Rails/Devise: Couldn't find User with 'id'=sign_out

I'm getting an error message from Rails that it could not find a user with id 'sign_out'. The error comes up when I try to log out of a user session. The application is looking at the GET route instead of the DELETE route that I would like it to.

I've looked through the other posts with similar errors and they suggest that the routes are not configured properly. But I can't seem to figure out what's going on with my application. I've tried several things:

  • Switching the order of the devise routes and the user resources
  • Calling out the delete method explicitly
  • Various combinations of method/destory paths for the link to logout

None of these options seem to work for me.

Here are my relevant files:

routes.rb

Rails.application.routes.draw do
  root to: 'welcome#index'
  devise_for :users
  resources :users, only: [:index,:show]

  resources :images, only: [:index, :show, :update]
  resources :challenges
end

I also tried nesting and calling out the path directly:

devise_for :users do
  get '/users/sign_out' => 'devise/sessions#destroy'
end
resources :users, only: [:index,:show]

my link to log out:

%li= link_to "Logout", destroy_user_session_path, :method => :delete

Running rake routes (relevant routes):

                  Prefix Verb   URI Pattern                       Controller#Action
    destroy_user_session DELETE /users/sign_out(.:format)         devise/sessions#destroy
                   users GET    /users(.:format)                  users#index

Using the "Log out" link gets this error:

Couldn't find User with 'id'=sign_out

and the parameters associated with the request are:

Request

Parameters:

{"id"=>"sign_out"}

And for whatever reason, the link still generates a GET request:

Started GET "/users/sign_out" for ::1 at 2015-12-25 03:35:11 -0600
Processing by UsersController#show as HTML
Parameters: {"id"=>"sign_out"}

Does anyone have any recommendations on what to change/try next? Let me know if you need more information from any other files.

jeudi 24 décembre 2015

Not getting a parameter

I'm trying to get a parameter of a number to record in the database. In the database does not record the number obtained in the input number.

inicializas_controller.rb

  class InicializasController < ApplicationController
  before_action :authenticate_user!  
  layout 'users_menus'

  def index
    @empresa = Parameter.find(1)

    if request.post?
      begin
        if Inicia.factura
          flash.now[:notice] = "Inicializado el Sistema de Facturacion"
        end  
       rescue
          flash.now[:notice] = "No se ha inicializado"
      end
    end 
  end
end

index.html.erb

<div class="container">
<h2 class="text-center">Inicializacion de Sistema</h2>
<p class="text-center">
  <%= bootstrap_flash %>
  <%= link_to 'Regresar Menu Principal', root_path, class: 'btn btn-default' %>
</p>

    <%= form_tag("/inicializas/index", method: "post") do %>
      <%= label_tag(:numero_factura, "Ingresar el numero de la ultima factura:") %>
      <%= number_field_tag(:numero_factura) %>
      <% @numero_factura = params[:numero_factura] %>
      <%= puts 'numero : ' + @numero_factura.to_s %>
      <%= submit_tag "Inicializar", class: Inicia.factura %>
    <% end %>
</div>

index appeared the "puts" on the console, params

inicia.rb

class Inicia

  def self.factura
    p = Time.new
    Invoice.destroy_all
    factura = Invoice.new
    factura.fecha = p.strftime("%d/%m/%Y") 
    factura.impuesto = 'S'
    factura.status_id = 1
    factura.customer_id = 1
    factura.fecha_vencimiento = p.strftime("%d/%m/%Y")
    factura.orden_compra = 'X'
    factura.pedido = 'X'
    factura.sale_id = 1
    factura.moneda = 'S/.'
    factura.numero_factura = params[:numero_factura]
    factura.save
    Rails.logger.info(factura.errors.inspect)
  end

  def self.get_date
    Time.now.strftime('%F')
  end
end

Error:

undefined local variable or method `params' for Inicia:Class

Hartl Rails Tutorial 5.3.4 Integration_test

On Hartl's Rails Tutorial, the instructions are to generate a template test with $ rails generate integration_test site_layout

I am getting the error /Users/AlfonsoGiron/.rvm/gems/ruby-2.2.1/gems/sprockets-3.5.2/lib/sprockets/manifest.rb:73:in 'read': Is a directory @ io_fread - /Users/AlfonsoGiron/sample_app/public/assets (Errno::EISDIR)' followed by multiple lines of from /Users/AlfonsoGiron/.rvm/gems/ruby-2.2.1 .. etc etc

So I can see its pointing to 'assets' in the directory. Not sure what I am supposed to do though to fix the error. Any ideas?

Ruby on rails execute show instead index

I have a resource called centers defined in routes.rb. When I get localhost:3000/centers centers_controller execute show action instead index. That should not happen according to Ruby on Rails CRUD documentation.

Any idea?

undefined method `email' for nil:NilClass link.user.email

In my index.html.erb file, I am getting an undefined method for email. I went into the rails console and tried running User.first.email and it worked perfectly. I tried taking out email and running link.user and that also worked. I am not sure why email is coming across as undefined when there is a user tied to a link and a user has an email. I am looking for some suggestions as to what may be going wrong.

Index.html.erb

<%= link.user.email %>

Schema with migrations already run

create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false

Heroku_can't upgrade to Cedar-14

As requested on Heroku, I am trying to upgrade from Cedar-10 to Cedar-14, but in vain. On my console, When I execute

heroku stack:set cedar-14

I get this:

 `stack:set` is not a heroku command.

Even if I've already installed the latest version of heroku toolbelt as proposed there (I am on Windows), I get the same error message

Many thanks

Trying to delete column from table using Rails migration?

I misspelled a word for a column and migrated the error, now I'm trying to delete the mistake from the schema and it doesn't seem that easy to do. I've deleted it out of the model and the schema by hand but it still shows up in the Rails Console when I make any changes to the database.

require builder returning false in rails 3

I am upgrading my rails application from rails 2.3 to rails 3.1. I am using builder like this

b = Builder::XmlMarkup.new :target => @data, :indent => 2

this works in rails 2.3 but not in 3.1.

Also, when i try to execute require 'builder' from rails console it works in rails 2.3 but says false in rails 3.1

Can anyone help. Thanks.

How to enable product quantity feature in free version of sharetribe?

I want to enable add quantity per product in my free version of sharetribe code. So can i enable that.

I think quantity feature is included in free version because i found column of quantity in database.

listings :-

t.string   "quantity"
t.string   "quantity_selector"

transactions :-

t.integer  "listing_quantity"

listing_units :-

t.string   "quantity_selector"

So how can i display quantity during listing and during buying item ?

getting error in passenger

cannot load such file -- rack (LoadError)
  /usr/local/rvm/rubies/ruby-2.1.1/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'
  /usr/local/rvm/rubies/ruby-2.1.1/lib/ruby/site_ruby/2.1.0/rubygems/core_ext/kernel_require.rb:54:in `require'
  /usr/local/rvm/gems/ruby-2.2.1/gems/passenger-5.0.14/lib/phusion_passenger/loader_shared_helpers.rb:395:in `activate_gem'
  /usr/local/rvm/gems/ruby-2.2.1/gems/passenger-5.0.14/helper-scripts/rack-preloader.rb:101:in `preload_app'
  /usr/local/rvm/gems/ruby-2.2.1/gems/passenger-5.0.14/helper-scripts/rack-preloader.rb:153:in `<module:App>'
  /usr/local/rvm/gems/ruby-2.2.1/gems/passenger-5.0.14/helper-scripts/rack-preloader.rb:29:in `<module:PhusionPassenger>'
  /usr/local/rvm/gems/ruby-2.2.1/gems/passenger-5.0.14/helper-scripts/rack-preloader.rb:28:in `<main>'

Generate gs1 128 barcode in Ruby on Rails

I am using barby gem to generate gs1-128 barcode. I am able to save the barcode in a .png file. Below is the code i am using,

def pti_label_preview   
    gtin_no =  params[:gtin_no]    
    barcode = Barby::GS1128.new(gtin_no,'C','12')   
    full_path = "#{Rails.root}/public/uploads/barcode.svg"
    File.open(full_path, 'w') { |f| f.write barcode.to_svg(:margin => 3, :xdim => 2, :height => 55) }
    render :text => path
  end

I created it by referring this. Barby::GS1128.new(gtin_no,'C','12') is accepting 3 argument, i want to know what are the 3 values i have to send to create barcode.

I have following values gs1_prefix, item no, check sum value, gtin no, lot no etc. What are the 3 values should i pass to GS1128 method

Rails where clause with a logic

I have a table where I am storing age ranges.

The age range is saved as Range object e.g. (1..4) in ruby. Now when I have to fetch all the records where one age falls in the age range. I have to do this

table.select{|s| s.age_range.include?(19)}

but this returns an array , not an active record relation object. So I would prefer doing something like:

table.where(s.age_range:  age_range.include?(19)}

which is obviously not correct. But its gets the point across. I would like to know if this is possible .

model.rb

class Model < ActiveRecord::Base
  attr_accessor :age_range_min, :age_range_max

  before_create :set_age_range
  serialize :age_range

  def set_age_range
    self.age_range = (age_range_min.to_i..age_range_max.to_i)
  end
end

mercredi 23 décembre 2015

Ruby on Rails remove activerecord relation result if certain criteria met

I have a rails site that allows a user to register two time slots for a course, once for themselves and once for their spouse. As courses fill up, I want to only have them displayed to the users that are registered so that they can un-register. Once the user un-registers, the course should be shown in the list again to indicate there is an open slot. I have everything working to do this, but I currently have the hiding of records being done in the view. Because of this, it is not showing the proper number of results per page as it is paginated. If there are 50 results on a page and 30 are hidden, it only shows 20 results on that page. What I wanted to do is see if I could possibly remove the Activerecord results from the list (NOT delete them) on the controller level. If there's another way to both hide the records and have the per page count be correct, I'd still be happy.

I have read up on the reject method, but don't see how it would be possible to do that in my scenario as I have to compare database values with the helper functions. There are also search functions and things of that nature which complicate by controller method. If there's an easy way to eliminate these from the Activerecord query itself, I'm just not seeing it. I'm not entirely sure that I can remove these from being visible in my scenario, other than doing so in the view like I am currently. I'm extremely close to just ditching pagination in this case, but as there are a couple hundred records to display I would rather not.

Helper Methods

def registered(course_session, user, spouse)
  course_attendee = CourseAttendee.where("user_id = ? and
   course_session_id = ? and for_spouse = ?", user.id, 
   course_session.id, spouse).first
  return course_attendee
end

def open_slots(course_session)
  course_attendees = CourseAttendee.where(:course_session_id =>
  course_session.id).count
  return course_session.attendee_limit - course_attendees
end

Current View Code

<% @course_sessions.each do |course_session| %>
    <% 
        ca = registered(course_session, current_user, false)
        cs = registered(course_session, current_user, true) 
        if ca || cs || (open_slots(course_session) > 0) %>
           ....show course session
        <% end %>
 <% end %>

What I'd like to do in Controller Index Method

def index
   if !params[:course_session_search].blank? &&
     !params[:course_session_search_end].blank?
      @course_sessions = CourseSession.joins(:room).order("starts_at").page(params[:page])
     .per_page(50).search(params[:course_session_search])   
   else
     @course_sessions = CourseSession.joins(:room).order("starts_at").
     page(params[:page]).per_page(50)
end

  # The do block is not actually there in the current code, this is my
  # attempt to weed out the unnecessary records
  @course_sessions.each do |course_session|
    ca = view_context.registered(course_session, current_user, false)
    cs = view_context.registered(course_session, current_user, true) 
    if !ca && !cs && (view_context.open_slots(course_session) <= 0)
       # Can I remove from display here if these conditions are met?
  end
end

respond_to do |format|
  format.html # index.html.erb
  format.json { render json: @course_sessions }
end

end

rspec gets "undefined method `build_rb_world_factory' for nil"

I'm updating a Rails 3.2 app to Ruby 2.2.2. I've pulled the Rails version up to 3.2.22, which is necessary for Ruby 2.2.2. That went relatively well but prompted a Cucumber update, from 1.2.1 to 1.3.20. (I don't recall the details, because that was several failed efforts ago, but I think my features were passing but then exiting false before I did this.)

Now Cucumber features run fine (albeit with a ton of unrelated Ruby 2.2.2 warnings), but rspec does not. Specifically, when I run rake spec I get this error:

/path/to/gems/cucumber-1.3.20/lib/cucumber/rb_support/rb_dsl.rb:15:in `build_rb_world_factory': undefined method `build_rb_world_factory' for nil:NilClass (NoMethodError)

The stack trace leads through Capybara (2.4.4, pinned for other reasons), ActiveSupport, and Bundler back up to rspec-core.

All my searches trying to find similar issues just lead to the code, because it seems like the only place this method name exists is in code.

Why am I getting this error from Capybara/Cucumber when running rspec? How can I fix it?

Can you recommend admin interface gem for Ruby on Rails 2.3.18

I have very old website in Ruby on rails 2.3.18 and I want to add admin interface like activeadmin but unable to install activeadmin in my project because of its old rails version (2.3.18) , If anyboday recommend any good admin interface gem or any hack to install activeadmin in rails 2.3.18 then it will be good.

Ability to like the post just one time

i'm working on the new ability on my RoR application. I've implemented the like/dislike system and now i'd like to add the ability to like the post just one time( User 1 can like or dislike the Post 2 just one time). How can i make this. I thought, that i can make it just like this

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
 # validates :avatar, attachment_presence: true
  has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }
  validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/

  has_and_belongs_to_many :posts

  def admin?
    admin
  end

end

 class Post < ActiveRecord::Base
  has_and_belongs_to_many :users
end

but besides of that i need one more field this has_and_belongs_to_many model, which will be the boolean field, that tells me if true - it is liked, false - it is disliked. BUt how can i access this field in this model. i do not have any idea ? Could you help me ?

Loaderror for mysql2 while starting ruby on rails app

I am trying to start the ruby on rails application that i had to my old mac which i transferred all data to the new one (el capitan).

I tried to bundle install, bundle update everything, the database.yml looks fine,but the application doesn't begin due to the following error.

I have two versions of mysql2, but if i delete the 0.4.2 and i try to bundle install (it installs 0.4.2) and if rails s (it requires the 0.4.2)

Any idea??

/Users/glouk/.rvm/gems/ruby-1.9.3-p448@global/gems/bundler-1.11.2/lib/bundler/rubygems_integration.rb:314:in `block in replace_gem': Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter` (can't activate mysql2 (~> 0.3.10), already activated mysql2-0.4.2. Make sure all dependencies are added to Gemfile.) (LoadError)

My gem list:

*** LOCAL GEMS ***

actionmailer (3.2.12)
actionpack (3.2.12)
activemodel (3.2.12)
activerecord (3.2.12)
activerecord-mysql2-adapter (0.0.3)
activeresource (3.2.12)
activesupport (3.2.12)
acts-as-taggable-on (2.3.3)
afm (0.2.0)
arel (3.0.3, 3.0.2)
Ascii85 (1.0.2)
awesome_nested_set (2.1.6)
bcrypt (3.1.10)
bcrypt-ruby (3.0.1)
beanstalk-client (1.1.1)
bigdecimal (1.1.0)
builder (3.0.4)
bundler (1.11.2)
bundler-unload (1.0.2)
cancan (1.6.10, 1.6.9)
capistrano (2.15.4)
climate_control (0.0.3)
cocaine (0.5.1)
cocoon (1.2.6, 1.1.2)
coffee-rails (3.2.2)
coffee-script (2.2.0)
coffee-script-source (1.10.0, 1.6.2)
combined_time_select (1.0.1, 1.0.0)
daemons (1.2.3, 1.1.9)
deep_cloneable (1.5.1)
devise (2.2.3)
diff-lcs (1.2.5, 1.2.4)
erubis (2.7.0)
exception_notification (2.5.2)
execjs (2.6.0, 1.4.0)
executable-hooks (1.3.2)
formtastic (2.2.1)
friendly_id (4.0.9)
galetahub-simple_captcha (0.1.5)
gem-wrappers (1.2.7)
has_scope (0.5.1)
hashery (2.1.0)
highline (1.7.8, 1.6.18)
hike (1.2.3, 1.2.2)
httpclient (2.7.0.1, 2.3.3)
i18n (0.7.0, 0.6.4)
impressionist (1.3.1)
inherited_resources (1.4.0)
io-console (0.3)
journey (1.0.4)
jquery-rails (2.2.1)
jquery-turbolinks (1.0.0)
jquery_datepicker (0.4)
json (1.8.3, 1.7.7, 1.5.5)
libv8 (3.16.14.13, 3.11.8.17)
liquid (3.0.6, 2.6.1)
mail (2.4.4)
mime-types (1.25.1, 1.23)
mimemagic (0.3.0)
mini_portile2 (2.0.0)
minitest (2.5.1)
multi_json (1.11.2, 1.7.2)
mysql (2.9.1)
mysql2 (0.4.2, 0.3.10)
negative_captcha (0.3.2)
net-scp (1.1.0)
net-sftp (2.1.1)
net-ssh (2.6.7)
net-ssh-gateway (1.2.0)
nokogiri (1.5.9)
orm_adapter (0.5.0, 0.4.0)
paper_trail (2.7.1)
paperclip (3.4.1)
pdf-core (0.6.0)
pdf-reader (1.3.3)
polyglot (0.3.5, 0.3.3)
rack (1.4.7, 1.4.5)
rack-cache (1.5.1, 1.2)
rack-ssl (1.3.4, 1.3.3)
rack-test (0.6.3, 0.6.2)
rails (3.2.12)
rails3-jquery-autocomplete (1.0.11)
railties (3.2.12)
rake (10.4.2, 10.0.4, 0.9.2.2)
rdoc (3.12.2, 3.9.5)
ref (2.0.0, 1.0.4)
responders (0.9.3)
roo (1.11.2)
rspec-core (2.99.2, 2.13.1)
rspec-expectations (2.13.0)
rspec-mocks (2.99.4, 2.13.1)
rspec-rails (2.13.2)
ruby-ole (1.2.11.6)
ruby-rc4 (0.1.5)
rubygems-bundler (1.4.4)
rubyzip (1.1.7, 0.9.9)
rvm (1.11.3.9)
rvm-capistrano (1.3.0)
sass (3.4.20, 3.2.8)
sass-rails (3.2.6)
simple_form (2.1.0)
smarter_csv (1.1.0, 1.0.4)
social-share-button (0.1.4)
spreadsheet (0.8.5)
sprockets (2.2.3, 2.2.2)
sqlite3 (1.3.11, 1.3.7)
the_sortable_tree (2.3.2)
therubyracer (0.12.2)
thor (0.19.1, 0.18.1)
thread_safe (0.3.5)
tilt (1.4.1, 1.3.7)
treetop (1.4.15, 1.4.12)
truncate_html (0.9.3, 0.9.2)
ttfunk (1.4.0, 1.0.3)
turbolinks (1.1.1)
tzinfo (0.3.46, 0.3.37)
uglifier (2.0.1)
warden (1.2.4, 1.2.1)
will_paginate (3.0.7, 3.0.4)
xapian-ruby (1.2.21, 1.2.12)
xapian_db (1.3.2)

opening files in new tab without downloading them using javaScript or Ruby on Rails

I'm using AWS s3 for storing the files(CVs).

Nested Form not creating the record thats nested.

Hello I have 2 models Product and ProductSize. I create a ProductSize in an Product form.

Problem is, its not persisting creating the ProductSizes. You should be able to go product.product_sizes and a list of ProductSizes show.

product.rb

class Product < ActiveRecord::Base
  acts_as_taggable

  belongs_to :user
  belongs_to :category

  has_many :product_sizes
  has_many :product_images, :dependent => :destroy

  validates :title, presence: true, length: { maximum: 30 }
  validates :description, presence: true, length: { maximum: 2000 }
  validates :category, :user, :price, presence: true

  accepts_nested_attributes_for :product_images, :product_sizes, allow_destroy: true
end

product_size.rb

class ProductSize < ActiveRecord::Base
  belongs_to :product
  belongs_to :size

  validates :quantity, presence: true
end

Here is my form. The way it works is: User can upload images, then select what category the Product is for. Lets say they select Shirt, then a list of all shirt sizes will drop down like XS, Small, Medium, Large. Then the user puts what quantity they have for the sizes they have. Like 13 XS shirts and 4 large Shirts.

<%= javascript_include_tag "custom" %>
<div class="container">
  <div class=“row”>
    <div class="col-md-6 col-md-offset-3">
      <div class="panel panel-primary">
        <div class="panel-body">
          <%= simple_nested_form_for @product do |f| %>
            <%= f.fields_for :product_images do |product_image| %>
              <% if product_image.object.new_record? %>
                <%= product_image.file_field(:product_image) %>
                <%= product_image.link_to_remove "Remove Image", data: { confirm: "Are you sure you want to delete this image?" } %>
              <% else %>
                <%= product_image.hidden_field :_destroy %>
              <% end %>
            <% end %>
            <p><%= f.link_to_add "Add a image", :product_images, :data => { :product_image => "#product_images" } %></p>
            <%= f.collection_select :category_id, @categories, :id, :name, include_blank: true, prompt: "Select One Category" %>

            <% @categories.each do |category| %>
              <div class='sizes_container' id ='sizes_container_for_<%= category.id %>'>
                <% category.sizes.each do |size| %>
                  <%= label_tag "product_form[sizes_by_id][#{size.id}]", size.title %>
                  <%= text_field_tag "product_sizes_attributes[sizes_quantity][#{size.id}]" %>
                <% end %>
              </div>
            <% end %>

            <%= f.input :title, label:"Title"%>
            <%= f.input :price, label:"Price"%>
            <%= f.input :description,label:"Description" %>
            <%= f.input :size_description, label:"Size Details"%>
            <%= f.input :shipping_description, label:"Shipping Details"%>
            <%= f.input :tag_list,label:"Tags - Seperate tags using comma ','. 5 tags allowed per product" %>
            <%= f.button :submit, "Create new product", class: "btn-lg btn-success" %>
          <% end %>
        </div>
      </div>
    </div>
  </div>
</div>

Here are what my params look like at the create action.

    36: def create
 => 37:   binding.pry
    38:   @product = Product.new product_params
    39:   @product.user_id = current_user.id
    40:   if @product.save
    41:     redirect_to @product
    42:     flash[:success] = "You have created a new product"
    43:   else
    44:     flash[:danger] = "Your product didn't save"
    45:     render "new"
    46:   end
    47: end

**[1] pry(#<ProductsController>)> product_params**
=> {"title"=>"test",
 "price"=>"3325",
 "description"=>"test",
 "tag_list"=>"test",
 "category_id"=>"3",
 "size_description"=>"test",
 "shipping_description"=>"test",
 "product_images_attributes"=>
  {"0"=>
    {"product_image"=>
      #<ActionDispatch::Http::UploadedFile:0x007f8cb786a010
       @content_type="image/jpeg",
       @headers="Content-Disposition: form-data; name=\"product[product_images_attributes][0][product_image]\"; filename=\"780069_black_l.jpg\"\r\nContent-Type: image/jpeg\r\n",
       @original_filename="780069_black_l.jpg",
       @tempfile=#<File:/var/folders/yx/znmx6qfj0c507bvkym6lvhxh0000gn/T/RackMultipart20151223-46388-p07o84.jpg>>,
     "_destroy"=>"false"},
   "1450863732810"=>
    {"product_image"=>
      #<ActionDispatch::Http::UploadedFile:0x007f8cb7869e08
       @content_type="image/jpeg",
       @headers="Content-Disposition: form-data; name=\"product[product_images_attributes][1450863732810][product_image]\"; filename=\"20090a.jpg\"\r\nContent-Type: image/jpeg\r\n",
       @original_filename="20090a.jpg",
       @tempfile=#<File:/var/folders/yx/znmx6qfj0c507bvkym6lvhxh0000gn/T/RackMultipart20151223-46388-n9mzf2.jpg>>,
     "_destroy"=>"false"}}}

[2] pry(#<ProductsController>)> params
=> {"utf8"=>"✓",
 "authenticity_token"=>"jfh6vsb1N1zhAIFyzer4liwuV+iHQ+P8pF6mZHUyF8IXNn6oXqnLDse84jnrP3BKI889CWigIDqVMJncxOYZ9Q==",
 "product"=>
  {"product_images_attributes"=>
    {"0"=>
      {"product_image"=>
        #<ActionDispatch::Http::UploadedFile:0x007f8cb786a010
         @content_type="image/jpeg",
         @headers="Content-Disposition: form-data; name=\"product[product_images_attributes][0][product_image]\"; filename=\"780069_black_l.jpg\"\r\nContent-Type: image/jpeg\r\n",
         @original_filename="780069_black_l.jpg",
         @tempfile=#<File:/var/folders/yx/znmx6qfj0c507bvkym6lvhxh0000gn/T/RackMultipart20151223-46388-p07o84.jpg>>,
       "_destroy"=>"false"},
     "1450863732810"=>
      {"product_image"=>
        #<ActionDispatch::Http::UploadedFile:0x007f8cb7869e08
         @content_type="image/jpeg",
         @headers="Content-Disposition: form-data; name=\"product[product_images_attributes][1450863732810][product_image]\"; filename=\"20090a.jpg\"\r\nContent-Type: image/jpeg\r\n",
         @original_filename="20090a.jpg",
         @tempfile=#<File:/var/folders/yx/znmx6qfj0c507bvkym6lvhxh0000gn/T/RackMultipart20151223-46388-n9mzf2.jpg>>,
       "_destroy"=>"false"}},
   "category_id"=>"3",
   "title"=>"test",
   "price"=>"3325",
   "description"=>"test",
   "size_description"=>"test",
   "shipping_description"=>"test",
   "tag_list"=>"test"},
 "product_sizes_attributes"=>{"sizes_quantity"=>{"1"=>"3", "2"=>"4", "3"=>""}},
 "commit"=>"Create new product",
 "controller"=>"products",
 "action"=>"create"}

[3] pry(#<ProductsController>)> params[:product_sizes_attributes]
=> {"sizes_quantity"=>{"1"=>"3", "2"=>"4", "3"=>""}}

Rails3 assets are failed to compile on new servers

We have had an amount of servers in AWS, successfully running rails3 application on ubuntu10. We use capistrano for deploy. Servers are behind the load balancer, running unicorns behind nginx.

One day we updated the configuration and turned on two new servers running ubuntu14. We deployed the app onto them in staging mode, made sure everything goes well, and re-deployed the app there as production.

After new servers were turned on, we started to encounter problems on some requests with assets pipeline: not all assets were available. I suspect there was kinda désynchronisation between old good ubuntu10s and new ubuntu14. The reproducible behaviour is:

  • 14 on ⇒ some assets fail;
  • 14 off ⇒ everything is great.

We tried to clean / recompile assets manually, with no luck. I believe there is something really easy I am missing. So, my question would be: how to properly introduce new servers, running Rails3 app, in Amazon farm, so that assets are not messed up?

mardi 22 décembre 2015

How send_two_factor_authentication_code method is invoked on devise sign in?

I need to invoke this method of devise two factor authentication after i got successful login of create method of sessions controller.
But how should i use this inside create action? Thanks in advance.

Setting up the liked/disliked attribute which is array-type

I have a like/dislike sytem on my web application. But there's a problem: I need that the user can like the post just one time(no more), but don't know how can i implement this. I thought, that i can make a new model, which will be connetcted via :trough.

Like/dislike system using AJAX

I'm currently working on my first RoR project. For now i'd like to make integrate a like/dislike system into my application. I have some code, but it works just only when the page is reloaded. My goal is to make the ability to like/dislike a post without reloading the page(using Ajax, not the built-in one). So, here's my code, what is wrong here ?

My controller

def like
    @post=Post.find(params[:id])
    @post.increment!(:like)
    render :nothing => true, :status => 200
  end

  def dislike
    @post=Post.find(params[:id])
    @post.increment!(:dislike)
    render :nothing => true, :status => 200
  end

my view

<table>
  <% if @post.count!=0 %>
    <% @post.each do |p| %>
      <%if !p.text.nil?%>
        <tr data-post_id="<%= p.id %>">
       <td><b class="margin"><h4><%=p.text%></b></h4></td>
       <td>by <%= link_to p.user.username, profile_dashboard_path(p.user) %>&nbsp;&nbsp; </td>
       <td><span class="glyphicon glyphicon-thumbs-up likeAction"><%=  p.like %> </td>
       <td><span class="glyphicon glyphicon-thumbs-down dislikeAction"><%= p.dislike %> </td>
      <%end%>
    <% end %>
  <%else%>
    There's no posts yet, but you can add <%=link_to "one", create_a_post_dashboard_path(current_user)%>
  <%end%>
</table>

my js file, which is located in app/assets/javascripts/dashboard.js, so i dont have any js file with the name like.js.erb or dislike.js.erb(i'm not sure if i need them)

jQuery(function($) {
  $(".likeAction").click(function(){
    var current_post_tr = $(this).parents('tr')[0];
    $.ajax({
      url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/like',
        type: 'PUT',
        success: function(){
          $(".likeAction").hide().fadeIn();
          location.reload();
        }
     });
  });

  $(".dislikeAction").click(function(){
    var current_post_tr = $(this).parents('tr')[0];
    $.ajax({
      url: 'http://localhost:3000/dashboard/' + $(current_post_tr).attr('data-post_id') +'/dislike',
        type: 'PUT',
        success: function(){
          $(".dislikeAction").hide().fadeIn();
          location.reload();
        }
    });
  });
});

Rails: validate uniqueness of two columns (together)

I have a Release model with medium and country columns (among others). There should not be releases that share identical medium/country combinations.

How would I write this as a rails validation?

Searchkick ransack conflict

After setting up the searchkick is showing this message:

undefined method `aggs' for Ransack::Search>:Ransack::Search

someone have the same problem with searchkick and ransack?

thank's

Rails "hidden" rows counting toward pagination count

I have a rails site that allows users to register for sessions. This list tries to filter out spaces where there are available slots and only displays an unregister button to the users that have already registered. The problem I have is that it only shows my per page count less the number of records that are hidden. For instance, 30 sessions are full but there are 50 per page, it shows 20 sessions. There is a varying limit of space per session, which must be checked (called attendee_limit).

I am using the code below. If I could easily page by one of my fields (start_date) or show a total of 50 per page as normal, I'd be happy. I cut out the majority of the view code but included the if statement to determine if it should be displayed. I figure I need to do this controller side to filter out those results entirely, but can't think of a good way to approach it due to the need to still allow users to unregister. Any idea of how I can accomplish this without just ditching pagination?

Helper methods

def registered(course_session, user)
  attendee = Attendee.where("user_id = ? and course_session_id = ?",
    user.id, course_session.id).first
  return attendee
end

def open_slots(course_session)
  attendees = Attendee.where(:session_id => course_session.id).count
  return course_session.attendee_limit - attendees
end

View

<% @course_sessions.each do |course_session| %>
<% 
  isreg = registered(course_session, current_user)
  if isreg || (open_slots(course_session) > 0) %>
    <!-- Display index -->
<% end %>
<% end %>
<%= will_paginate @course_sessions %>

Controller

def index
  @course_sessions = CourseSession.joins(:room).order("starts_at")
   .page(params[:starts_at]).per_page(50)
  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @course_sessions }
end

end

Clicking Edit button on first record in view does not Get

I have a view with 2 buttons as follows:

<td>
  <div style="float: left; width: auto;">
    <%= button_to 'Edit', edit_jobitem_path(:id => p.id), :method => :get %>
  </div>
 <%= button_to 'Destroy', p, :method => :delete, data: { confirm: 'Are you sure?' } %>
</td>

Both buttons work fine, with one very strange exception: The Edit button on the first record Posts (the parent Jobs record) instead of Gets (the child JobItems record).

Any ideas what could be happening here?

Thanks!

Google favicon crawler causing ActionView::MissingTemplate exception on Rails 3.2

I got an ActionView::MissingTemplate exception every time Google Favicon crawler tries to get my root url accepting only the image/* format.

The crawler user agent is:

Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20110814 Firefox/6.0 Google Favicon

I can reproduce this exception with this command:

curl -v -H "Accept: image/*" http://localhost:3000

I'm using a custom layout, named omega (on /layouts/omega path), can this affect the framework like that?

Isn't this a misbehavior?

The error log:

ActionView::MissingTemplate at /
================================

> Missing template /layouts/omega/_index with {:locale=>[:"pt-br", :pt, :en], :formats=>["image/*"], :handlers=>[:erb, :builder, :coffee]}. Searched in:
  * "/home/samuel/www/myapp/app/views"
  * "/home/samuel/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/kaminari-0.16.3/app/views"
  * "/home/samuel/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/declarative_authorization-0.5.7/app/views"
  * "/home/samuel/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/devise-3.4.1/app/views"
  * "/home/samuel/www/myapp"
  * "/"


app/controllers/properties_controller.rb, line 280
--------------------------------------------------

``` ruby
  275             redirect_to root_path, status: :moved_permanently
  276           else
> 280             render '/layouts/omega/_index'
  282           end
  283         end
  284         return
  285       end
```

App backtrace
-------------

 - app/controllers/properties_controller.rb:280:in `show'

Full backtrace
--------------

 - actionpack (3.2.22) lib/action_view/path_set.rb:58:in `find'
 - actionpack (3.2.22) lib/action_view/lookup_context.rb:122:in `find'
 - actionpack (3.2.22) lib/action_view/renderer/abstract_renderer.rb:3:in `find_template'
 - actionpack (3.2.22) lib/action_view/renderer/template_renderer.rb:28:in `block in determine_template'
 - actionpack (3.2.22) lib/action_view/lookup_context.rb:143:in `with_fallbacks'
 - actionpack (3.2.22) lib/action_view/renderer/abstract_renderer.rb:3:in `with_fallbacks'
 - actionpack (3.2.22) lib/action_view/renderer/template_renderer.rb:28:in `determine_template'
 - actionpack (3.2.22) lib/action_view/renderer/template_renderer.rb:10:in `render'
 - actionpack (3.2.22) lib/action_view/renderer/renderer.rb:36:in `render_template'
 - actionpack (3.2.22) lib/action_view/renderer/renderer.rb:17:in `render'
 - actionpack (3.2.22) lib/abstract_controller/rendering.rb:110:in `_render_template'
 - actionpack (3.2.22) lib/action_controller/metal/streaming.rb:225:in `_render_template'
 - actionpack (3.2.22) lib/abstract_controller/rendering.rb:103:in `render_to_body'
 - actionpack (3.2.22) lib/action_controller/metal/renderers.rb:28:in `render_to_body'
 - actionpack (3.2.22) lib/action_controller/metal/compatibility.rb:50:in `render_to_body'
 - actionpack (3.2.22) lib/abstract_controller/rendering.rb:88:in `render'
 - actionpack (3.2.22) lib/action_controller/metal/rendering.rb:16:in `render'
 - actionpack (3.2.22) lib/action_controller/metal/instrumentation.rb:40:in `block (2 levels) in render'
 - activesupport (3.2.22) lib/active_support/core_ext/benchmark.rb:5:in `block in ms'
 - /home/samuel/.rbenv/versions/2.2.2/lib/ruby/2.2.0/benchmark.rb:303:in `realtime'
 - activesupport (3.2.22) lib/active_support/core_ext/benchmark.rb:5:in `ms'
 - actionpack (3.2.22) lib/action_controller/metal/instrumentation.rb:40:in `block in render'
 - actionpack (3.2.22) lib/action_controller/metal/instrumentation.rb:83:in `cleanup_view_runtime'
 - activerecord (3.2.22) lib/active_record/railties/controller_runtime.rb:24:in `cleanup_view_runtime'
 - actionpack (3.2.22) lib/action_controller/metal/instrumentation.rb:39:in `render'
 - app/controllers/properties_controller.rb:280:in `show'
 - actionpack (3.2.22) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
 - actionpack (3.2.22) lib/abstract_controller/base.rb:167:in `process_action'
 - actionpack (3.2.22) lib/action_controller/metal/rendering.rb:10:in `process_action'
 - actionpack (3.2.22) lib/abstract_controller/callbacks.rb:18:in `block in process_action'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:492:in `block in _run__3499709650331313942__process_action__3074038669074245940__callbacks'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:215:in `block in _conditional_callback_around_548'
 - marginalia (1.3.0) lib/marginalia.rb:77:in `record_query_comment'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:214:in `_conditional_callback_around_548'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:447:in `_run__3499709650331313942__process_action__3074038669074245940__callbacks'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:405:in `__run_callback'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:385:in `_run_process_action_callbacks'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:81:in `run_callbacks'
 - actionpack (3.2.22) lib/abstract_controller/callbacks.rb:17:in `process_action'
 - actionpack (3.2.22) lib/action_controller/metal/rescue.rb:29:in `process_action'
 - actionpack (3.2.22) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action'
 - activesupport (3.2.22) lib/active_support/notifications.rb:123:in `block in instrument'
 - activesupport (3.2.22) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
 - activesupport (3.2.22) lib/active_support/notifications.rb:123:in `instrument'
 - actionpack (3.2.22) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
 - actionpack (3.2.22) lib/action_controller/metal/params_wrapper.rb:207:in `process_action'
 - activerecord (3.2.22) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
 - actionpack (3.2.22) lib/abstract_controller/base.rb:121:in `process'
 - actionpack (3.2.22) lib/abstract_controller/rendering.rb:45:in `process'
 - rack-mini-profiler (0.9.7) lib/mini_profiler/profiling_methods.rb:106:in `block in profile_method'
 - actionpack (3.2.22) lib/action_controller/metal.rb:203:in `dispatch'
 - actionpack (3.2.22) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
 - actionpack (3.2.22) lib/action_controller/metal.rb:246:in `block in action'
 - actionpack (3.2.22) lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
 - actionpack (3.2.22) lib/action_dispatch/routing/route_set.rb:36:in `call'
 - journey (1.0.4) lib/journey/router.rb:68:in `block in call'
 - journey (1.0.4) lib/journey/router.rb:56:in `call'
 - actionpack (3.2.22) lib/action_dispatch/routing/route_set.rb:608:in `call'
 - mongoid (2.4.11) lib/rack/mongoid/middleware/identity_map.rb:33:in `block in call'
 - mongoid (2.4.11) lib/mongoid.rb:133:in `unit_of_work'
 - mongoid (2.4.11) lib/rack/mongoid/middleware/identity_map.rb:33:in `call'
 - warden (1.2.3) lib/warden/manager.rb:35:in `block in call'
 - warden (1.2.3) lib/warden/manager.rb:34:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
 - rack (1.4.7) lib/rack/etag.rb:23:in `call'
 - rack (1.4.7) lib/rack/conditionalget.rb:25:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/head.rb:14:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/flash.rb:242:in `call'
 - rack (1.4.7) lib/rack/session/abstract/id.rb:210:in `context'
 - rack (1.4.7) lib/rack/session/abstract/id.rb:205:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/cookies.rb:341:in `call'
 - activerecord (3.2.22) lib/active_record/query_cache.rb:64:in `call'
 - activerecord (3.2.22) lib/active_record/connection_adapters/abstract/connection_pool.rb:479:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:405:in `_run__4348557046124021977__call__3061323192353778014__callbacks'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:405:in `__run_callback'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
 - activesupport (3.2.22) lib/active_support/callbacks.rb:81:in `run_callbacks'
 - actionpack (3.2.22) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/reloader.rb:65:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
 - better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'
 - better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'
 - better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
 - railties (3.2.22) lib/rails/rack/logger.rb:32:in `call_app'
 - railties (3.2.22) lib/rails/rack/logger.rb:16:in `block in call'
 - activesupport (3.2.22) lib/active_support/tagged_logging.rb:22:in `tagged'
 - railties (3.2.22) lib/rails/rack/logger.rb:16:in `call'
 - quiet_assets (1.1.0) lib/quiet_assets.rb:27:in `call_with_quiet_assets'
 - actionpack (3.2.22) lib/action_dispatch/middleware/request_id.rb:22:in `call'
 - rack (1.4.7) lib/rack/methodoverride.rb:21:in `call'
 - rack (1.4.7) lib/rack/runtime.rb:17:in `call'
 - activesupport (3.2.22) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
 - rack (1.4.7) lib/rack/lock.rb:15:in `call'
 - actionpack (3.2.22) lib/action_dispatch/middleware/static.rb:83:in `call'
 - rack-cache (1.2) lib/rack/cache/context.rb:136:in `forward'
 - rack-cache (1.2) lib/rack/cache/context.rb:245:in `fetch'
 - rack-cache (1.2) lib/rack/cache/context.rb:185:in `lookup'
 - rack-cache (1.2) lib/rack/cache/context.rb:66:in `call!'
 - rack-cache (1.2) lib/rack/cache/context.rb:51:in `call'
 - honeybadger (2.0.6) lib/honeybadger/rack/error_notifier.rb:33:in `block in call'
 - honeybadger (2.0.6) lib/honeybadger/config.rb:189:in `with_request'
 - honeybadger (2.0.6) lib/honeybadger/rack/error_notifier.rb:30:in `call'
 - honeybadger (2.0.6) lib/honeybadger/rack/user_feedback.rb:29:in `call'
 - honeybadger (2.0.6) lib/honeybadger/rack/user_informer.rb:19:in `call'
 - rack-mini-profiler (0.9.7) lib/mini_profiler/profiler.rb:276:in `call'
 - railties (3.2.22) lib/rails/engine.rb:484:in `call'
 - railties (3.2.22) lib/rails/application.rb:231:in `call'
 - rack (1.4.7) lib/rack/content_length.rb:14:in `call'
 - railties (3.2.22) lib/rails/rack/log_tailer.rb:17:in `call'
 - thin (1.6.3) lib/thin/connection.rb:86:in `block in pre_process'
 - thin (1.6.3) lib/thin/connection.rb:84:in `pre_process'
 - thin (1.6.3) lib/thin/connection.rb:53:in `process'
 - thin (1.6.3) lib/thin/connection.rb:39:in `receive_data'
 - eventmachine (1.0.7) lib/eventmachine.rb:187:in `run'
 - thin (1.6.3) lib/thin/backends/base.rb:73:in `start'
 - thin (1.6.3) lib/thin/server.rb:162:in `start'
 - rack (1.4.7) lib/rack/handler/thin.rb:13:in `run'
 - rack (1.4.7) lib/rack/server.rb:268:in `start'
 - railties (3.2.22) lib/rails/commands/server.rb:70:in `start'
 - railties (3.2.22) lib/rails/commands.rb:55:in `block in <top (required)>'
 - railties (3.2.22) lib/rails/commands.rb:50:in `<top (required)>'
 - script/rails:6:in `<main>'

Upgrading from rails 2 to 3: undefined method use_standard_json_time_format

I am trying to upgrade rails from 2.3 to 3.1. I have referred the upgrade video from rails cast but i am having some difficulties.

Steps i have followed till now.
1. Create a separate rails-3 branch from stable branch.
2. Update & reload rvm to the latest version.
3. gem install rails -v 3.0.20
4. rails upgrade check and rails upgrade backup using rails upgrade plugin
5. rails new . --skip-active-record

when i start the server i am getting this error

initializers/new_rails_defaults.rb:13:in `<top (required)>': undefined method `use_standard_json_time_format=' for ActiveSupport:Module (NoMethodError)

can anyone please help. Thanks.

Refinery CMS on Ruby Rails: Translating / Localising the Strings in the Blog Module

In the blog module for refinery CMS there are some strings in the source code that I would like to translate. When I override the view for _post.html.erb of the blog module there is code like this inside:

 <%= content_tag(:span, 
   "#{t('by', :scope => 'refinery.blog.posts.show')} #{@post.author.username}",
   :class => "blog_author") if @post.author.present? %>

I would like to localize the "by" string, so that in the blog, the default english "By authorname" is replaced by a phrase in another language.

Now, I have modified the en.yml and hr.yml localisation files in the rails config/locales directory and added the translation. However, this makes no effect to the strings displayed on my page.

I have tried setting the config.i18n.default_locale variable in config/application.rb to :en and to my desired language but this also accomplishes nothing.

The furthest I came was that if I change the config.current_locale variable in initializers/refinery/i18n.rb to :de for example, that has the effect of translating the admin interface for refinery and its blog module. And yet, the strings in the blog entries remain the same.

I have also added a yml file with translations for my locale in the gems library of the refinery blog component, but it still does not work.

Any help on how to translate the strings in the refinery blog module would be appreciated. I have searched the internet on how to translate refinery, but haven't managed to find any specific information for the translation of the the blog component, only general guides for rails, which don't seem to help with the refinery blog.

I am using the following gems versions:

  • rails (4.2.4)
  • rails-i18n (4.0.7)
  • railties (4.2.4)
  • refinerycms (3.0.0 1d13007)
  • refinerycms-acts-as-indexed (2.0.1)
  • refinerycms-authentication-devise (1.0.4)
  • refinerycms-blog (3.0.0 5ee8336)
  • refinerycms-core (3.0.0 1d13007)
  • refinerycms-i18n (3.0.1 ff93ad9)
  • refinerycms-images (3.0.0 1d13007)
  • refinerycms-pages (3.0.0 1d13007)
  • refinerycms-resources (3.0.0 1d13007)
  • refinerycms-search (3.0.0 aa8098c)
  • refinerycms-settings (3.0.0)
  • refinerycms-wymeditor (1.0.6) ...

Thank you in advance!

-- M. Jakov

How to integrate payu money payment gateway in rails 4

How to integrate Payu Money in rails 4.

I have not found any proper documentation.

I use this gem http://ift.tt/1Pi6cwl

but in this i got some error when i run 'rails s'.

ERROR :

/home/tps/.rvm/gems/ruby-2.2.0/gems/active_merchant_payu_in-0.0.1/lib/active_merchant_payu_in.rb:2:in `require': cannot load such file -- active_merchant/billing/integrations (LoadError)

Upgrading Rails: rails new . creating a new directory new in the project folder

I am trying to upgrade rails from 2.3 to 3.1. I have referred the upgrade video from rails cast but i am having some difficulties.

Steps i have followed till now.
1. Create a separate rails-3 branch from stable branch.
2. Update & reload rvm to the latest version.
3. gem install rails -v 3.0.20
4. rails upgrade check and rails upgrade backup using rails upgrade plugin
5. rails new .

The step 5 is where i am facing issue this is creating a separate application in a folder named "new" in a sub directory and this is not over writing the current application as per the video in rails cast.

Can anyone please help. What am i doing wrong? Thanks.

lundi 21 décembre 2015

Rails Active Records SQLite3::SQLException: no such column: subs.subscriber_id: SELECT "subs".* FROM "subs" WHERE "subs"."subscriber_id" =?

I have Used Has_many relation to a Subscriber and Sub models

class Sub < ActiveRecord::Base

belongs_to :Subscriber end

class Subscriber < ActiveRecord::Base has_many :subs

end

While inserting record to Sub table bu sung << It is giving error as follows

Rails Console. a=Subscriber.find(1) Subscriber Load (0.0ms) SELECT "subscribers".* FROM "subscribers" WHERE "subscribers"."id" = ? LIMIT 1 [["id", 1]] => # irb(main):002:0> a.subs Sub Load (0.0ms) SELECT "subs".* FROM "subs" WHERE "subs"."subscriber_id" = ? [[nil, 1]] ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: subs.subscriber_id: SELECT "subs".* FROM "subs" WHERE "subs"."subscriber_id" = ?