jeudi 31 mars 2016

Dropzone Rails ActionView::MissingTemplate

After added format: :html on the action controller dropzone work on developmen but on production mode still shows: someone is having the same issue?

ActionView::MissingTemplate: Missing template banners/new, application/new with {:locale=>[:"pt-BR", :pt], :formats=>[:json], :handlers=>[:erb, :builder, :coffee]}. Searched in:

Multiple t.references get nil value for the second nested models

I have visits who belongs_to owner, and belongs_to car through two t.references, owner_id keeps getting nil when I create new visit through @car.visits.create.

Visit.rb

class Visit < ActiveRecord::Base
#validates :notes, presence:true
belongs_to :car
belongs_to :owner
end

Owner.rb

class Owner < ActiveRecord::Base
has_many :cars
has_many :visits    
accepts_nested_attributes_for :visits
accepts_nested_attributes_for :cars
end

Car.rb

class Car < ActiveRecord::Base
belongs_to :owner
has_many :visits
end

The migration for Visit

class CreateVisits < ActiveRecord::Migration
def change
create_table :visits do |t|
  t.boolean :open
  t.text :notes
  t.references :owner
  t.references :car
  t.timestamps null: false
end

end
end

if I

 car1 = Car.create(......)
 car1.visits.create(.....)

I get the value of Visit.owner_id = nil, however, car_id is perfectly filled with the right relation.

what am I missing? Help is much appreciated.

example from my console where owner_id: nil even when its created from a @car who has already owner_id

gemset rails folder empty

I am using ruby 1.9.3-p551 with rvm and try to install rails 3.2.17 with bundler. After bundle install and bundle show rails I see an empty rails folder. Is this normal? I am wondering why I can still start my rails server. After starting the server I get 500 page error.

Masquerading with Warden

In my Rails app I'm using Warden with my own strategy. I'm not using Devise.

As an administrator, I would now like to log in as another user by pressing a simple button.

Is this possible?

Post wordpress search result to Ruby on rails application

I am not a developer, i just install, optimize and maintain wordpress sites. So we've got a client who wants to have a site where the front end is powered by wordpress and the backend is powered by ruby on rails.

I've finished building the front end site with wordpress and our developers did their jobs in ROR.

Now my problem is i have a search box on the home page where a user inputs his address and the address gets validated by smartystreets.

All i have to do now is post the validated info to a registration form in the ruby on rails app.

Below is the code of wordpress search form.

<form method="post" action=""><input type="text" name="street" placeholder="<?php echo esc_attr($placeholder);?>" class="search"  value="<?php echo the_search_query(); ?>"/>
<input type="submit" id="searchsubmit" value="">
</form>

Guys please help me out

Rails. Is the way to access to params hash from model concern?

I need to access to params inside my concern

module UrlGenerator
  extend ActiveSupport::Concern
  def test
    params[:slug]
  end 
end

How can i do? Thanks

Save each JSON object to a model

I'm looking to save each JSON object within the call to a model so I don't have to call the API every single time I load up the application, instead I call all the models entries.

require 'httparty'
require 'json'

class Feed < ActiveRecord::Base
  include HTTParty
  base_uri 'http://ift.tt/1SoPMRI'

  # GET /feeds
  # GET /feeds.json
  def boom
    response = self.class.get("/tVv8nTahbhgkyIUW8ByCe0-7/last_ready_run/data?&format=json")
    @elements = response.parsed_response["image"]
    @parsed = @elements.collect { |e| e['url'] }
  end

This is what I currently have within my model, which perfectly calls the API and displays each one of them within my view. Obviously this isn't the greatest way of doing this, I would like to save each of the JSON's URL property to my model - not entirely sure how to go about doing this!

Rails Httpclient 2.7.1 : OpenSSL::SSL::SSLError: Could not generate secret

I am getting error

OpenSSL::SSL::SSLError: Could not generate secret
    from ...../httpclient-2.7.1/lib/httpclient/jruby_ssl_socket.rb:504:in `initialize'
    from ..../httpclient-2.7.1/lib/httpclient/jruby_ssl_socket.rb:442:in `create_socket'
    from ..../httpclient-2.7.1/lib/httpclient/session.rb:739:in `connect'

Is anyone faces same?

How to reduce loading time while export to excel in ruby on rails

How to reduce loading issue while export to excel , i have a lot of records i want to export to excel if i click on button its taking lot of time to export on ruby on rails ? is their any backgroud gems ?

mercredi 30 mars 2016

Rails 3: feedjira gem for RSS

I am using feedjira gem

Feedjira::Feed.fetch_and_parse("rss_url")

above method fetches all the rss feeds from that url but is there any method/option in feedjira which fetches messages at particular timeframe? (like I want feeds for only last 24 hours)

Thanks in advance.

Ruby on Rails: Polymorphic Association Confusion

I am contributing one of the ruby on rails application over GitHub where I faced the following scenario:

I am having following models which I want to convert to make polymorphic:

class Comment < ActiveRecord::Base
  belongs_to :team
  belongs_to :user
  belongs_to :application
  belongs_to :project
end

class Team < ActiveRecord::Base
  has_many :comments
end

class Project < ActiveRecord::Base
  has_many :comments
end

class User < ActiveRecord::Base
end

class Application < Rails::Application
end

I made following changes to make it polymorphic:

Perform database change to removed team_id, project_id, application_id and user_id and added commentable_id and commentable_type to comments table.

Modifications in models:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
end

class Team < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Project < ActiveRecord::Base
  has_many :comments, as: :commentable
end

As described within rails guides.

I am confused to change in following models:

class User < ActiveRecord::Base
end

class Application < ActiveRecord::Base
end

Should I need following changes in User and Application model?

class User < ActiveRecord::Base
  has_many :comments, as: :commentable
end

class Application < ActiveRecord::Base
  has_many :comments, as: :commentable
end

Thanks in Advance!

multi-search and dynamic pg_search_scope in the same model

I am using PgSearch to build both simple and advanced search in a Rails app.

Can I use multi-search and dynamic pg_search_scope in the same model? I want to use the multi-search for the simple search and the dynamic scope for the advanced search among multiple attributes of multiple models.

I tried putting both multisearchable and dynamic pg_search_scope as described in the documentation, in my model. But it returns this error "tried to create Proc object without a block".

How did I get a user with sign_in_count 0 in devise?

My admin dashboard page started choking due to a division by 0, which it turns out was due to a user getting a sign_in_count of 0.

Does anyone have ideas on how this could have happened, or how I can find out what happened?

Various info that could be useful:

  • I can see that the user actually did manage to use the site, performing actions that requires the current_user functional.

  • This is user over #7000 on my site, so it's not a normal configuration error.

  • The current_sign_in_at and current_sing_in_ip was not set at all - they are nil.

  • Using Rails 3.2.21, Ruby 2.0.0, Devise 3.2.4.

  • The user created his account using google+.

This is my authentication.rb code that is being run for google+:

        newuser = User.where(:email => user_email).first_or_create!(:password => *a_generated_password*)
        newuser.save
        newuser.authentications << auth
        auth.post_frequency = Authentication::PF_NOPOST
        auth.save
        newuser.save
        newuser.profile.tryAutomaticNewRealName(auth)
        flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => auth.provider.capitalize
        sign_in_and_redirect auth.user, :event => :authentication

I know that newuser.profile.tryAutomaticNewRealName(auth) executed correct because the real name was stored.

fields that don't pass validations don't get .field_with_errors class

My validations work fine

class Owner < ActiveRecord::Base
validates :car_number, :name, :phone, presence:true
validates_uniqueness_of :car_number 
has_many :cars
has_many :visits
accepts_nested_attributes_for :visits

and my save.js.erb

$("ul.errors").html("")
<% if  @owner.errors.any? %>
<% @owner.errors.full_messages.each do |message| %>
$("ul.errors").append($("<li />").html("<%= message.html_safe %>"))
$('.field_with_errors').addClass('has-error has-feedback');

<% end
else %>

$("#new_owner_div").html("<%= j (render 'visits/show', { :f => @visit })%>")
<%end%>

but no fields get under class 'field_with_errors'.

mardi 29 mars 2016

Rails Nested form and Dropzone

i'm striving to make a simple dropzone work on a product form with nested images form but after search a lot and change the code i would like to know if dropzone support nested form, because i can't find it in the doc.

anyway my code is:

$('#images').dropzone({// PDF dropzone element
  maxFilesize: 2, // Set the maximum file size to 256 MB
   maxFiles: 10,
    dictDefaultMessage: "drop your images here",
    paramName: "product[images_attributes][][foto]",
  addRemoveLinks: true, // Don't show remove links on dropzone itself.
 dictRemoveFile: 'Remover'

    // rest of code
 //
 });

<

%= form_for @product, :html => {:multipart => true}  do |p| %>
  <div class="block margin_top">

 <%= p.fields_for(:images,  html: { multipart: true, id: "images",class: "dropzone"}) do |i| %>
     <div class="fallback">

            <%= i.file_field :photo %><br>
            <%= i.submit "Save" %>
          </div>
    <% end %>
</div>

Retrieving an object in a jbuilder partial return 'nil' unless it is wrapped in an array

I am trying to use a jbuilder to render a json response for a TypeCar object in my response

class TypeCar < ActiveRecord::Base
  attr_accessible :name

  belongs_to :car_alias, foreign_key: :name, primary_key: :name, counter_cache: true
  has_one :main_car, through: :car_alias, foreign_key: :name, primary_key: :name

end

In the json for the TypeCar partial, "views/api/type_cars/_type_cars.json.jbuilder",

json.extract! type_car, :name

json.main_car Array.wrap(type_car.main_car) do |main_car|
    json.partial! "api/main_cars/main_cars", main_car: main_car
end

And the main car partial in "api/main_cars/_main_cars.json.jbuilder"

json.extract! main_car, :more_info, :name, :id

The view that uses the _type_car partial, returns the following

{
name: test,
main_car: [
{
more_info: "Lorem Ipsum",
name: "New",
id: 198
}
]

I am guessing that the for main car attribute is a hash in a single object array because of wrapping up the array. But I would like the remove this as it is one more extra level of nesting that is not needed. So I would just prefer a plain dictionary instead of a hash.

The reason I had to wrap the object in an array and pass it to an enumerable was because nothing else seemed to work.

This...

json.extract! type_car, :name

json.main_car do 
    json.partial! "api/main_cars/main_cars", main_car: type_car.main_car
end

Gives this error...

undefined method `more_info' for nil:NilClass

And this:

json.extract! type_car, :name

json.main_car type_car.main_car do |main_car|
    json.partial! "api/main_cars/main_cars", main_car:main_car
end

Gives this error:

undefined method `map' for #<MainCar:>

Even trying stuff like type_car.main_car.id within the type car partial returns the nil problem.

Really appreciate all the help and guidance, thanks!

Using jbuilder in rails to construct an array of objects with different classes

A model(FirstModel) in my rails app has a has_many relationship with another model(Item).

class FirstModel < ActiveRecord::Base

  has_many :items, :dependent => :destroy

  def item_array
    a = []
    self.items.each do |item|
      a.push(item.item_thing)
    end
    a
  end
end

Item itself belongs :item_thing through a polymorphic association. A method on FirstModel returns an array of "items", not the join model object(which is of class Item), but the item_thing of each Item object, and therefore it is an array of objects of different classes (checked in rails console, and the method returns the array just fine)

class Item < ActiveRecord::Base
  belongs_to :item_thing,  :polymorphic => true


end

In my show.json.jbuilder for FirstModel, I want to take that array of "items" and use different templates based on which class the item belongs to. The following file path is "views/api/items/show.jbuilder"

json.extract! @item, :name

json.items @item.item_array do |item|
  if item.class == 'Book'
    json.partial! 'api/books/show', item
  end
  if item.class == 'Car'
    json.partial! 'api/cars/show', item
  end
end

The car and book template paths are "views/api/cars/show.json.jbuilder" and "views/api/books/show.json.jbuilder.

When I get the json from the above template the name of the FirstModel object is visible, items array is empty, whereas I am trying to get an array of hashes for each item, rendered through its respective template.

Thank you for helping!

Multiple time data store using pubnub?

I have developed a android chatting application in which users can talk to only customer care team subscribe to five specific channel i.e Laundry, Food, HomeServices etc. I am using PubNub to full-fill this requirement. But now, I have faced some issues regarding multiple entries of the same data. I am storing chat messages data in my server when users send messages to customer care(at the time of listening) or vice versa(at the time of publishing). But now, I am facing two serious issues if no customer care executive is online data is not getting stored in the database and if customer care executive account is logged on multiple devices it store the chat message twice in the database sent by the customer.

Rails: I don't get any error messages in my loge file only 500 page

I have a rails 3 app which is running with puma. When open localhost:3000 there is always the 500 page shown. I've tried to set binding.pry and log messages across the files (e.g. ApplicationController), but it seems they are never reached. I changed the root path to a controller that does not exist, still no log messages. So it seems like the route is never reached as well. I ve looked into the rails log, puma log, rack log but nothing is shown. Any idea how to get appropriate error messages? Please help, I am so frustrated, looking for the erros for days.

failed models validation input don't go under field_with_errors class

Inputs for @task that fail validations, don't go under field_with_errors, no change of classes

         class Task < ActiveRecord::Base
         #VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

         validates :title, presence:true , 
         validates :date_of_task, presence: true
         #validates :email, format: { with: VALID_EMAIL_REGEX }

         end

is there any pre configuration that should be made to start putting failed validation inputs under that class ?

Rails Gem To create Hashtag

do you know if it exists a gem or a jquery plugin to create hashtag in ruby on rails like Twitter et Facebook ?

Or could we code it to have the result. I wanna create a search by #hastag in my search bar.

Thank you for your backs.

How to Fetch Pdf Field Properties from downloads folder in ruby on rails from linux(ubuntu) vm

I have a pdf file in download folder , and i want to fetch particular field properties in that pdf file. How to fetch in ruby on rails

How to write Active record to search based on all values in a table field

How to search based on all locations. Locations are stored in cookie , i want to search and get result like this, list properties in locations Delhi NCR or Mumbai or Pune or Hyderabad or Bangalore or Chennai or Coimbatore or Cochin

i written active record like this

@location = cookies[:location_id] (here iam getting all locations) @properties=Property.where("location LIKE ?", "%#{@location}%")

so that i got sql query like this SELECT * FROMpropertiesWHERE (location LIKE '%Delhi NCR,Mumbai,Pune,Hyderabad,Bangalore,Chennai,Coimbatore,Cochin%')

seperated by comma, and also not getting search result if any location name is present in table. how to search according to all locations and list if any present?

lundi 28 mars 2016

Filter through nested JSON object and obtain JSON with specific keys, using Ruby

I currently have a nested JSON object which resembles

{
"People": [
    {
        "Name": "James",
        "Age": "18",
        "Gender": "Male",
        "Sports": []
    },
    {
        "Name": "Sarah",
        "Age": "19",
        "Gender": "Female",
        "Sports": [
            "Soccer",
            "Basketball",
            "Football"
        ]
    }
] 
}

Being new to Ruby, I aim to filter throught the entire json and return only the json object/objects in which the "Sports" array has content. So in the above scenario I expect to obtain the object below as a final outcome:

    {
        "Name": "Sarah",
        "Age": "19",
        "Gender": "Female",
        "Sports": [
            "Soccer",
            "Basketball",
            "Football"
        ]
    }

Will I have to initiate a new method to perform such an act? Or would using regular ruby calls work in this case?

Accessing input.val() at client side in order to render partial with parameters

I have an input with id "searcha", trying to perform a live search

    <input type="input" id="searcha" placeholder="Search">

I can't find a way to pass the $('#searcha').val() to render on keyup()

 $('#searcha').keyup(function(){
 $('#index-table').html('<%= j (render index, :locals => query: $('searcha').val() ) %>')
  })

and How should I be passing params[:query] to the controller ?

Add comments to posts = undefined local variable or method `post' for

Hi there I have an error like this undefined local variable or method 'post' for #<#<Class:0x007ffc40469ad0>:0x007ffc40461088>

I don't understand because I create a partial in post which names _comments.html.erb

<p class="text-center">Poster un commentaire</p>
      <%= simple_form_for [post, post.comments.new] do |f| %>
        <%= f.error_notification %>
        <%= f.input :content, label: "Commentaire"%>
        <%= f.submit "Envoyer", class: "btn btn-primary" %>
      <% end %>

and it render like that <% render 'comments' %>

The undefined method is in this line <%= simple_form_for [post, post.comments.new] do |f| %>

the model post is has_many :comments, dependent: :destroy

the model post is has_many :comments, dependent: :destroy

the model comment is belongs_to :user belongs_to :post

The route is resources :posts do resources :categories resources :comments end

Comments controller is

class CommentsController < ApplicationController

before_action :set_post

def create
  @comment = @post.comments.build(comment_params)
  @comment.user_id = current_user.id

  if @comment.save
    flash[:success] = "You commented the hell out of that post!"
    redirect_to :back
  else
    flash[:alert] = "There is a problem with your comment"
    render root_path
  end
end

def destroy
  @comment = @post.comments.find(params[:id])

  @comment.destroy
  flash[:success] = "Comment deleted :("
  redirect_to root_path
end

private

def set_post
  @post = Post.find(params[:post_id])
end

def comment_params
  params.require(:comment).permit(:content, :post_id, :user_id)
end
end

Thank you so much for your help.

How to fetch users browsing location and store in cookie in rails

i want to store user selected location as cookie. if location is not selected automatically it should fetch users browsing location and store as a cookie value. How to do so?

i have done the code like this when user selects a location, location is storing as cookie now by this code.

@location = Location.find(location).name if location.present? cookies[:location_id] = { :value => @location, :expires => Time.now + 3600}

But i don't have any idea to fetch users browsing location automatically and store in cookie.

Please help me to do this.

Any help is appreciatable.

dimanche 27 mars 2016

How to write active record with and and or conditions in ruby

i want to write active record with 3 and condition(must) and two or conditions i have written like this.

@properties=Property.where(category_id: 2).where(status: 3).where(p_type: 'sell')

this lists me the query with and conditions true , here i need to include two or conditions at end, how to do so?, it tried like this but gives error

@properties=Property.where(category_id: 2).where(status: 3).where(p_type: 'sell').or(location: @location).or(featured: '1)

Please help. Any help is appreciatable

Creating a rails relationship object in a has_many through association

I have 3 models A, B and C with the following relationship:

A has_many :Bs
A has_many :Cs, through: :Bs, source: :C

Now i want to create a relationship object of model B like this:

@B = A.Bs.create!(B_params)

which does create an object of B with the correct A_id and C_id, however calling A.Cs does not return anything. It works if i do something like A.Cs << C, but after adding additional columns to the relationship model, I'd like to create the middle man directly, but still access the has_many part directly. Any options in the model to achieve that directly or what would be the 'best' workaround (something like

A.Cs << C
A.B.last.update_attributes(B_params)

)?

samedi 26 mars 2016

Where to put jquery files including event handlers

I know it might be stupid, but as always help is appreciated:

I have pre.js file containing one event handler

$('#soon_tasks_header').click(function(){ $('#soon_tasks_content').slideToggle() ; })

it is required in application.js

     //= require pre

clicking on #soon_tasks_header doesn't toggleslide it, However, putting the code in the jQuery console in my browser works fine.

Note:

when I tested this in my pre.js file, it worked fine:

$(document).ready(function(){
alert('aaaa') })

I think I am messing something fundamental, which is importing jquery files, where and when.

Uncaught ReferenceError: XXXX is not defined

I got a very weird bug which I've spent a couple of hours to solve but that just didn't work. The code is shown below:

class Post extends React.Component {
  render () {
    return (
      <div>
        <div>TEST</div>
      </div>
    );  
  }
}

This works fine but if I added something like var XXX = require('XXX'). It will say, Uncaught ReferenceError: Post is not defined, which doesn't make sense to me at all. What's more interesting is that if you create your react component like the following approach:

var MyComponent = React.createClass(/*...*/); 

This will not work if you have require module in front unless you remove the var and it works magically.

So, I don't know if that's a problem of my rails project or something goes wrong with ES6.

Does anyone have similar problem before?

vendredi 25 mars 2016

Having issues in saving with Ruby on Rails

I'm trying to make a todo list with Rails, first I have made the List and it's specs, everything went okay, but then I've began to make it's items, but it simple don't save it's content, it stores a empty string, it don't work neither on the form or on the specs. When I try to save with the Rails console everything goes okay.

This is the message I receive from Rspec:

Creating todo items is successful with valid content
 Failure/Error: expect(page).to have_content("Ruby")
   expected to find text "Ruby" in ""

Above is the code for...

#todo_item_controller.rb

class TodoItemsController < ApplicationController
  def index
    @todo_list = TodoList.find{ params[:todo_list_id] }
  end

  def new
    @todo_list = TodoList.find{ params[:todo_list_id] }
    @todo_item = @todo_list.todo_items.new
  end

  def create
    @todo_list = TodoList.find(params[:todo_list_id])
    @todo_item = @todo_list.todo_items.new(todo_item_params)
    if @todo_list.save
      flash[:success] = "Added todo list item."
      redirect_to todo_list_todo_items_path
    else
      flash[:error] = "Something went wrong"
      render action: :new
    end
  end

  private
    def todo_item_params
      params[:todo_item].permit{:content}
    end
end

#index.html.erb

<h1><%= @todo_list.title %></h1>

<ul class="todo_items">
  <% @todo_list.todo_items.each do |todo_item| %>
    <li><%= todo_item.content %></li>
  <% end %>
</ul>
<p>
  <%= link_to "New Todo item", new_todo_list_todo_item_path %>
</p>

#new.html.erb

<%= form_for [@todo_list, @todo_item] do |form| %>
  <%= form.label :content %>
  <%= form.text_field :content %>

  <%= form.submit "Save" %>
<% end %>

When it appear on the browser it displays only the list symbol but no content.

Sorry for too long

can I use multi-search and dynamic pg_search_scope in the same model?

I am using PgSearch to build both simple and advanced search in a Rails app. Can I use multi-search and dynamic pg_search_scope in the same model? I want to use the multi-search for the simple search and the dynamic scope for the advanced search among multiple attributes of multiple models. I tried putting both the multisearchable and the dynamic pg_search_scope as described in the documentation, in my model. But it returns this error "tried to create Proc object without a block".

No route matches {:action=>“show”...} missing required keys: [:id] when accessing New Action?

Why is happening this when I'm trying to access the action new?

enter image description here

routes.rb

resources :tvseries

tvseries_controller.rb

class TvseriesController < ApplicationController
  before_action :set_tvseries, only: [:show, :edit, :update, :destroy]

  # GET /tvseries
  # GET /tvseries.json
  def index
    @tvseries = Tvserie.all
  end

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

  # GET /tvseries/new
  def new
    @tvseries = Tvserie.new
  end

  # GET /tvseries/1/edit
  def edit
  end

  # POST /tvseries
  # POST /tvseries.json
  def create
    @tvseries = Tvserie.new(tvseries_params)

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

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

  # DELETE /tvseries/1
  # DELETE /tvseries/1.json
  def destroy
    @tvseries.destroy
    respond_to do |format|
      format.html { redirect_to tvseries_url, notice: 'Tvserie was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  # GET /all_tv_series
  def all
    @tv_series = Tvserie.all
  end

  # GET /tv_series/add_language/1
  # GET /tv_s/add_language/1.json
  def add_subtitles
    @languages = Language.all
  end

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def tvseries_params
      params.require(:tvseries).permit(:title, :image, :description)
    end
end

Associate two already existing objects using Has And Belongs To Many

I'm making an App in Rails to show anime, these animes has and belongs to many languages, so I made a HABTM association:

class Anime < ActiveRecord::Base
  has_and_belongs_to_many :languages
end

class Language < ActiveRecord::Base
  has_and_belongs_to_many :animes
end

Now I don't know how can I make associations between them, I've created many Languages' records to use them, for example, Language with ID 1 is English, Language with ID 2 is Spanish, etc... And I want to just make the associations between an anime and a language, ie, if I want to say that the Anime with ID 1 it's available in Spanish only, then in the table animes_languages I want to create the record with values anime_id: 1 and language_id: 2 and nothing more, but I belive that if I execute the command Anime.find(1).languages.create it will not use an already existing language, it will create a new language, but the only thing I want is to make associations between already existing animes with already existing languages, so, How can I do this? Should I make a model for the table animes_language?

It's confusing for me cause when I created that table as specified here enter link description here, I created the table without ID, it only have the fields anime_id and language_id.

Rails: Missing polymorphic: true Association Option

I've inherited a database and am trying to make sense of the associations.

In my Agent model:

class Agent < ActiveRecord::Base
  has_many :created_events, :class_name => "Event", :as => :creator
  has_many :created_tasks, :class_name => "Task", :as => :creator
  ....
end

In my Event model:

class Event < ActiveRecord::Base
  belongs_to :creator, :class_name => 'Agent'
  ....
end

In my Task model: class Task < ActiveRecord::Base belongs_to :creator, :class_name => 'Agent' ... end

What type of association is this? What is it doing?

In my research, all of the examples either use polymorphic: :true - for polymorphic associations, or foreign_key: - to set the foreign key directly. Neither of these association options are present in any of my models.

jeudi 24 mars 2016

Rails File Management and Email Distribution combined

I'm looking to have a file manager on my rails app - similar to dropbox (I was going to follow this tutorial: http://ift.tt/1m1wurD) but I am also trying to allow users to share the file via emailing it out to a contact list of emails saved in the app. I currently have a contact list in my members controller with :email as one of my fields. I am unsure where how to go about this. Are there any gems anyone would recommend?

A small puzzle of Rails Associations

There are 2 tables. One is User(id, name, email) and the other is Student(id, who_id).

I wanna Use this way:

Student.find(id).name, Student.find(id).email

rather than:

User.find(student.who_id).name, User.find(student.who_id).email

to get data.

How should I do?

btw, I cannot change who_id to user_id for any reason.


class User < ActiveRecord::Base
end

class Student < ActiveRecord::Base
end

Rails session prevent navigation

In my controller I save the form data into session when user post the request to create new Invoice. But once in invoice page, I cant navigate away to another page because the session still not cleared. Following were my code.

def new

        @invoice = Invoice.new

        #post request from detail page to invoice along with variable from form
        if request.post?     

            @invoice.booking_date = params[:datepicker]
            @invoice.product_id = params["product-id"]
            @invoice.variants = params[:variant]

            #if user not signed in, user redirected to sign in page before    
            #continue to post invoice page with form data saved in session
            if !user_signed_in?
                session[:pending_invoice] = @invoice
                return redirect_to new_user_session_path

            end

            #following for case where user already signed in before directed to 
            #invoice page
            set_extra_params_for_new
            @invoice_params = {}
            @contact_detail_params = {}

        else

            #this is when user are from sign in page with session present. This is 
            #the code that make the issues where I cant navigate away to other 
            #pages until I cleared the session with session[:pending_invoice] = 
            #nil.
            if (session[:pending_invoice].present?) && (session[:pending_invoice].instance_of? Invoice)

                @invoice = session[:pending_invoice]
                set_extra_params_for_new

                @invoice_params = {}

                @contact_detail_params = {}

            else
                #this code for params post request that comes from payment gateway. So  
                #all the data in invoice page is intact
                @invoice.booking_date = params[:invoice][:booking_date]
                @invoice.product_id = params[:invoice][:product_id]
                @invoice.coupon_id = params[:invoice][:coupon_id]
                @invoice.coupon_amounts = params[:invoice][:coupon_amounts]
                @coupon_amounts_with_user_currency = params[:invoice][:coupon_amounts_with_user_currency]
                @invoice.variants = params[:variant]
                set_extra_params_for_new

                @invoice_params = params[:invoice]

                #session[:pending_invoice] = nil

            end
        end

        set_invoice_currency_attributes(@invoice)

        gon.invoice = @invoice
        gon.real_total_with_currency = @invoice.real_total_with_currency
        gon.real_total = @invoice.real_total


    end

Now the issues, if i cleared the session with #session[:pending_invoice] = nil, user wont be able to refresh the page. It will cause an error. How can I resolve this kind of issue? Thanks!!

Rails Admin - Delete not available for some records

I got an old app that uses Rails Admin for its admin section. Its a great tool! Minimum code, maximum punch! But I am experiencing a problem.

Some records are not possible to delete through the administrative interface. This is because there exists no 'delete' button.

What could be preventing the delete link from been generated?

Notes

  • In the console I was able to delete the record using offer.destroy
    • This means that there are no callbacks preventing the delete, isn't it?
  • The application is Rails 3.2
  • Using Rails Admin 0.4
  • snap

Rails 3: How to override a Gem Method

version : Rails 3.2.22.2

I'm using Impressionist gem to track user activity. This gives me ActiveModel::MassAssignmentSecurity::Error I wan tot override the impression.rb module from the gen to use attr_accessible I tried 2 things -> 1: Create an impression.rb file under app/models

class Impression
  def hello
    "hello world"
  end
end

In initializer/impression.rb,

require 'impression'

when I try the following on console

a = Impression.first
a.hello

I get method not found error

2: I added the code in the initializezs/impression.rb file

Impression.class_eval do
    def hi
        puts 'you got me!'
    end
end

and I still go the same error as in point 1.

How can I effectively override the Gem model?

There was an error while trying to load the gem 'zxing'. Rails 4.2

I am trying to add gem 'zxing' into my project, but got this message after running the server

C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'zxing'. (Bundler::GemRequireError)
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/bundler-1.11.2/lib/bundler.rb:99:in `require'
        from C:/Sites/seas/config/application.rb:8:in `<top (required)>'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:78:in `require'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:78:in `block in server'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:75:in `tap'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:75:in `server'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
        from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/railties-4.2.5.1/lib/rails/commands.rb:17:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `<main>'

any suggestion?

Error in starting rails server in local - Puma - runner.rb:103:in `reopen'- No such file or directory @ rb_io_reopen

I am facing the following error in trying to start the rails server, locally. The repository in the production environment working fine. Recent version from production is cloned into local. The only change was in the rails version in gemfile; changed from ruby '2.2.1' to ruby '2.2.3'. Following the bundle update, this problem/error displays, on trying to start the rails server.

I am using a mac, the users directory is Users/circle. (issue could be related to puma version, rvm version and gem file versions). But any hints and suggestions in this regards would be greatly appreciated. 

[3951] Puma starting in cluster mode...
[3951] * Version 3.2.0 (ruby 2.2.3-p173), codename: Spring Is A Heliocentric Viewpoint
[3951] * Min threads: 1, max threads: 6
[3951] * Environment: development
[3951] * Process workers: 2
[3951] * Phased restart available
[3951] * Listening on tcp://localhost:3000
[3951] Use Ctrl-C to stop

/Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/puma-3.2.0/lib/puma/runner.rb:103:in `reopen': No such file or directory @ rb_io_reopen - /Users/circle/Test_new/testdirectory/shared/log/puma.stdout.log (Errno::ENOENT)
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/puma-3.2.0/lib/puma/runner.rb:103:in `redirect_io'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/puma-3.2.0/lib/puma/cluster.rb:40:in `redirect_io'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/puma-3.2.0/lib/puma/cluster.rb:408:in `run'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/puma-3.2.0/lib/puma/launcher.rb:172:in `run'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/puma-3.2.0/lib/rack/handler/puma.rb:51:in `run'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/server.rb:286:in `start'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/server.rb:80:in `start'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:80:in `block in server'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /Users/circle/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

Don't delete impressions when soft deleting a record

I'm using impressionist gem to lock the views for different products. I'm also having soft-deletion in my application. When I remove any record/product, its impressions also got deleted.

I just want to keep the impressions and don't want to delete it on Record deletion. Any idea, how i can do it ?

using

ruby 2.2.2
Rails 4.2.4
impressionist (1.5.1)

Jruby NoSuchMethodError: org.jruby.RubyClass.defineMethod

Environment

  • JRuby version : jruby 9.0.0.0 (2.2.2) 2015-07-21 e10ec96 Java HotSpot(TM) 64-Bit Server VM 25.65-b01 on 1.8.0_65-b17 +jit [linux-amd64]

  • Java version ➜ trunk java -version java version "1.8.0_65" Java(TM) SE Runtime Environment (build 1.8.0_65-b17) Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode)

  • Operating system and platform

    ➜ trunk uname -a Linux swapnil-Lenovo-Z50-70 4.2.0-27-generic #32-Ubuntu SMP Fri Jan 22 04:49:08 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

    ➜ trunk lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 15.10 Release: 15.10 Codename: wily

Relevant info:

Expected Behavior

rails c should start a rails console

Actual Behavior

Exception : LoadError: load error: hpricot_scan -- java.lang.NoSuchMethodError: org.jruby.RubyClass.defineMethod(Ljava/lang/String;Lorg/jruby/runtime/callback/Callback;)V

➜  trunk rails c
/home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/prawn-core-0.8.4/lib/prawn/core.rb:34: warning: already initialized constant VERSION
LoadError: load error: hpricot_scan -- java.lang.NoSuchMethodError: org.jruby.RubyClass.defineMethod(Ljava/lang/String;Lorg/jruby/runtime/callback/Callback;)V
           require at org/jruby/RubyKernel.java:940
  block in require at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/activesupport-3.2.22.1/lib/active_support/dependencies.rb:251
   load_dependency at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/activesupport-3.2.22.1/lib/active_support/dependencies.rb:236
           require at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/activesupport-3.2.22.1/lib/active_support/dependencies.rb:251
             <top> at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/hpricot-0.8.6-java/lib/hpricot.rb:20
           require at org/jruby/RubyKernel.java:940
   block in (root) at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/bundler-1.11.2/lib/bundler/runtime.rb:1
              each at org/jruby/RubyArray.java:1560
  block in require at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/bundler-1.11.2/lib/bundler/runtime.rb:77
              each at org/jruby/RubyArray.java:1560
           require at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/bundler-1.11.2/lib/bundler/runtime.rb:72
           require at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/bundler-1.11.2/lib/bundler/runtime.rb:61
             <top> at /home/swapnil/.rvm/gems/jruby-9.0.0.0@JayApp/gems/bundler-1.11.2/lib/bundler.rb:99
           require at org/jruby/RubyKernel.java:940
             <top> at /home/swapnil/Rails/Lab/MA-JRuby/trunk/config/application.rb:15
           require at org/jruby/RubyKernel.java:940
             <top> at script/rails:6

mercredi 23 mars 2016

Is there any QR Decoder for rails (pure ruby)

I'm now using 'qrio' but it seem to work only with string contain only lower case English.Otherwise there will be random error convertion message eg. "incompatible character encodings: UTF-8 and ASCII-8BIT"

Are there any other QR Decoder for rails (pure ruby) ?

Rails 3 -> Ahoy plugin for user activity tracking

I have installed the Gem Ahoy as per the instruction in the link -> http://ift.tt/1euzW8q

Add this line to your application’s Gemfile:

gem 'ahoy_matey'

And add the javascript file in app/assets/javascripts/application.js after jQuery.

//= require jquery
//= require ahoy

MySQL or SQLite

Add activeuuid to your Gemfile.

gem 'activeuuid', '>= 0.5.0'

And run:

rails generate ahoy:stores:active_record
rake db:migrate

The visit.rb module gets created fine but on rails console, I get 'Table doesn't exist' error

Visit
 => Visit(Table doesn't exist) 

How can I configure Ahoy with my Ruby application

Adding Profile Object automatically after Devise/Rails successful Sign Up

I'm having some trouble figuring out how to automatically create a user profile object as soon as a user has signed up using devise. My profile object has been scaffolded out, now its a case of adding the empty Profile.new object to the user object. The following code is from registrations_controller.rb

  protected

  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.for(:sign_up) << :profile_id
  end

  # The path used after sign up.
  def after_sign_up_path_for(resource)
    p "$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"

    resource.profile << Profile.new
    p resource
    super(resource)
  end

What happens is that in the Rails console, the p '$$$$..' line is visible and there are no errors. However, in psql when looking at the profile_id is null. I've been scratching my head for hours, is this even the best way to do this, by passing it in the Devise's santizer?

We did think to instead redirect to the create_profile view that was scaffolded out, but in the case where a user signs up and then doesn't complete the profile, we'd have a problem. Does anyone have any advice on how to proceed, or how to pass the new Profile object in?

Rails Load Partial based on Media Querie

I'm trying to load a

menu bar

for @media (min-width: 768px) but i would like to remove the

menu bar

if @media (min-width: 480px)

so i thought in use a conditional but it just work for css.

have a way to not show a html partial based on the media querie?

thank's

mardi 22 mars 2016

Single count query taking too much time postgresql

explain analyze  SELECT COUNT(*) FROM "customers" WHERE (TRIM(telephone) = 
'06868787878' AND check_id = 41); 

                          QUERY PLAN                                                                      
------------------------------------------------------------------------------  
------------------------------------------------------------------- 
Aggregate  (cost=12982.58..12982.59 rows=1 width=0) (actual 
time=200.452..200.453 rows=1 loops=1) 
->  Bitmap Heap Scan on customers  (cost=544.59..12982.21 rows=147 width=0) 
(actual time=14.555..200.447 rows=1 loops=1) 
     Recheck Cond: (check_id = 41) 
     Filter: (btrim((telephone)::text) = '06868787878'::text) 
     Rows Removed by Filter: 29394 
     ->  Bitmap Index Scan on idx_customers_check_id  (cost=0.00..544.55 
   rows=29350 width=0) (actual time=9.669..9.669 rows=29395 loops=1) 
           Index Cond: (check_id = 41) 
  Total runtime: 200.750 ms 
 (8 rows) 

also sometimes its taking (293.6ms), (1956.3ms), is there any way to avoid this?

referencing an attribute in a windows path string

I have the following execute in chef:

#execute
execute 'service-api install' do
  command 'c:\buildinfo\service-api\api\approot\web-#{node['default']['env']}.cmd'
end

its running in windows and #{node['default']['env']} is an attribute that I am trying to reference in the path string above.

When I run this I get the following error:

> SyntaxError
> ==> default: -----------
> ==> default: C:\vagrant-chef\319622f1791bb50a8f9441fd4c1ff806\cookbooks\djcm_paypal_win\recipes\installService.rb:76:
> syntax error, unexpected tIDENTIFIER, expecting keyword_end
> ==> default: ...api\approot\web-#{node['default']['env']}.cmd'

If I try:

 #execute
    execute 'service-api install' do
      command "c:\buildinfo\service-api\api\approot\web-#{node['default']['env']}.cmd"
    end

The slashes display in a different color(escape character?) and I get the following error:

[execute] The filename, directory name, or volume label syntax is incorrect.
 command "c:\buildinfo ervice-api\api\approotweb-integration.cmd"

So it messes up around slashes but gets the attribute. How can I give an attribute in a string with slashes ?

Do initializers get loaded after app folder classes get loaded?

I am trying to debug some Carrierwave nonsense. This is what I understand so far:

I think this code in my carrierwave.rb initializer gets run after the app/uploader files are loaded. The reason why I think that is because my fixture files get uploaded to these directories defined here:

This is my carrierwave.rb initializer:

if Rails.env.test?

  ZipCodeCsvUploader
  StoryMainImageUploader

  # use different dirs when testing
  CarrierWave::Uploader::Base.descendants.each do |klass|
    next if klass.anonymous?
    klass.class_eval do
      def cache_dir
        "#{Rails.root}/spec/support/uploads/tmp/#{object_id}"
      end

      def store_dir
        "#{Rails.root}/spec/support/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
        # "#{Rails.root}/support/images/#{model.class.to_s.underscore}/#{mounted_as}/#{object_id}"
      end
    end
  end
end

The store_dir and the cache_dir seem to trump this app/uploaded file:

# encoding: utf-8
require 'carrierwave/processing/mime_types'

class StoryMainImageUploader < CarrierWave::Uploader::Base
  include CarrierWaveDirect::Uploader
  include CarrierWave::RMagick
  include CarrierWave::MimeTypes
  include S3DirectUploader

  process :set_content_type

  def store_dir
    "stories/#{model.id}/main_images"
  end

  def cache_dir
    "#{Rails.root}/support/uploads/tmp/#{object_id}"
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  version :medium do
    process :resize_to_limit => [800, 800]
  end

  version :thumb do
    process :resize_to_limit => [200, 200]
  end
end

None of the uploads will hit these files.

So my questions:

  1. Do the app files get loaded in a Rails app startup before the initializers?

  2. What do the lines:

    ZipCodeCsvUploader
    StoryMainImageUploader
    
    

do? How do we have access to these class names unless the classes were loaded first? Even if we do, what does calling these class names do?

Render external URL, from controller, in the same iframe

This is an embedded app in Shopify. I need to render a URL that allows the user to confirm a charge to their store. The URL is provided by Shopify, and I just need to render it. However, when I try with either of these options, it just hangs and the URL is never rendered.. BUT if I just copy and paste the URL into the browser it renders fine..

I tried with:

render @created_charge.confirmation_url
render :js => @created_charge.confirmation_url
redirect_to @created_charge.confirmation_url

And they didn't work.

The URL that needs to be rendered, looks like this:

http://ift.tt/1LELaKx
/confirm_recurring_application_charge?signature=XXXXX%2FYkHw%3D%3D--
9027c1eb56aXXXXXXXXXXXXX

lundi 21 mars 2016

setting up timezone between dokku and S3

I'm using dokku to host a rails application that uses aws-s3 SDK gem to upload files to S3. When I try to upload a file to the server, it gives me the following error in my logs:

Aws::S3::Errors::RequestTimeTooSkewed (The difference between the request time and the current time is too large.):

S3 bucket is in us-east-1 while the timezone on my server is set to Chicago timezone.

date Mon Mar 21 23:33:33 CDT 2016

When I tail the dokku logs, it shows me the time in UTC format:

2016-03-22T04:28:39.425196210Z prod[web.2]: I, [2016-03-22T04:28:39.422140 #154] INFO -- : worker=2 ready

How can I sync up my time between dokku and OS? Does my OS need to be in sync with S3 time? If so, there is no Chicago timezone S3 buckets.

/etc/timezone

America/Chicago

/etc/localtime is symlinked to /usr/share/zoneinfo/America/Chicago

Rails gem installed but throws error

looks like i have a problem trying to install rails gem.

so i followed the steps from this tutorial, I am using Ubuntu 14.04, rbenv and ruby version 2.2.3

Basically my error is:

apparently I installed rails gem successfully

$ gem install rails -v 4.2.4

-> Successfully installed rails-4.2.4

but whenever i try to use rails command, for example:

$ rails -v

-> bin/rails:9:in require': cannot load such file -- rails/commands (LoadError) from bin/rails:9:in'

I searched everywhere and noone seem to have the same problem as I do. I dont really know what to do now, any help will be really appreciated.

Thanks in advance!!

Is there a way to automatically update old Ruby on Rails queries to the newer syntax?

For example, update something from Rails 2 like

Model.find(:first, :conditions => ["column_a = ? and column_b = ?", 'string', object.id])

to a newer method that works such as

Model.where(column_a: 'string', column_b: object.id).first

I have a project where I need to update about a thousand more of these things than I originally thought. But I can't find any kind of gem, app, anything that can do these automatically. And it seems that with so many Rails apps upgrades someone would have. Anybody know of anything that can automate this process?

deleting from ruby array based on SQL query

I have a controller action that looks like this

def list
  @jobs = users_jobs_list_data
end

This is getting data from another action, user_jobs_list_data, which for simplicity's sake looks like this...

def users_jobs_list_data
  user_jobs_query = current_account.user_jobs).select("
    company_locations.name AS company_location_name")
    .joins("LEFT JOIN company_locations ON users.company_location_id = company_locations.id")

    ActiveRecord::Base.connection.exec_query(users_jobs_query.to_sql)
end

so the @jobs variable ends up coming in as an array rather than an activerecord relation. Here's where I am stuck. I am being passed a parameter which defines that only current records be shown. so now the action looks like this

def list
  if params[:current] == 'true'
    << show reduced results here >>
  else
    @jobs = users_jobs_list_data
  end
end

So the final piece is to reduce @jobs based on the criteria for current. This is where I am stuck. This is the code to access the current records

@jobs.where("'#{Date.today.iso8601}' between start_date and ifnull(end_date, '#{(Date.today + 1).iso8601}')")

This works fine on @jobs if @jobs is an activerecord relation, but not in this case, where @jobs is an array because I cannot call where on it. How can I resolve this bearing in mind @jobs really needs to stay as an array?

How to check sql commands executed using rake in Ruby on Rails

I have started my tutorials on Ruby on rails just a week ago I have got a doubt please guide me guys.

Rake

Rake utility allows you to create a job/task which uses rails environment. So say, you want to count the votes a user has given to an article and save it somewhere. You write a rake job, in which you can use Rails models and other helpers and get it done without going away from Rails.

I want to check all the SQL INSERT or CREATE lines executed when we do something like:

>$ bundle exec rake db:reset
>$ bundle exec rake db:seed
>$ bundle exec rake test:prepare

Is there a way I can do check the SQL commands in Ruby on Rails?

Solr not starting. Any idea why?

 bundle exec rake sunspot:solr:start
DEPRECATION WARNING: Support for Rails < 4.1.0 will be dropped. (called from warn at /Users/http://ift.tt/1S0t6XL)
Connecting to database specified by database.yml
Removing stale PID file at [file in solr file...]
Successfully started Solr ...

$ ps aux | grep solr
jeffrey.wan     59427   0.1  0.1  5099980  14924   ??  S    Thu03PM  12:39.85 /usr/bin/java -server -Xss256k -Xms512m -Xmx512m -XX:NewRatio=3 -XX:SurvivorRatio=4 -XX:TargetSurvivorRatio=90 -XX:MaxTenuringThreshold=8 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:ConcGCThreads=4 -XX:ParallelGCThreads=4 -XX:+CMSScavengeBeforeRemark -XX:PretenureSizeThreshold=64m -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=50 -XX:CMSMaxAbortablePrecleanTime=6000 -XX:+CMSParallelRemarkEnabled -XX:+ParallelRefProcEnabled -verbose:gc -XX:+PrintHeapAtGC -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+PrintTenuringDistribution -XX:+PrintGCApplicationStoppedTime -Xloggc:/Users/jeffrey.wan/.rbenv/versions/2.1.6/lib/ruby/gems/2.1.0/gems/sunspot_solr-2.2.4/solr/server/logs/solr_gc.log -Djetty.port=8982 -DSTOP.PORT=7982 -DSTOP.KEY=solrrocks -Duser.timezone=UTC -Djetty.home=/Users/http://ift.tt/1S0t6XN -Dsolr.solr.home=/Users/http://ift.tt/1VuWgE0 -Dsolr.install.dir=/Users/http://ift.tt/1S0t6qW -jar start.jar --module=http
jeffrey.wan      9004   0.0  0.0  2434840    772 s002  S+   10:06AM   0:00.00 grep solr

The processes don't show a solr process. Any idea why?

This is my sunspot.yml:

production:
  solr:
    hostname: localhost
    port: 8983
    log_level: WARNING
    # read_timeout: 2
    # open_timeout: 0.5

development:
  solr:
    hostname: localhost
    port: 8982
    log_level: INFO
    solr_home: solr
    path: /solr/collection1


test:
  solr:
    hostname: localhost
    port: 8981
    log_level: WARNING

ROR problems with cassandra

I use in my project Cassandra and after update ubuntu OS I catch next problems after start my RoR project:

Web application could not be started

No live servers in [#Thrift::BinaryProtocolAccelerated, :protocol_extra_params=>[], :transport=>Thrift::Socket, :transport_wrapper=>Thrift::FramedTransport, :raise=>true, :defaults=>{}, :exception_classes=>[IOError, Thrift::Exception, Thrift::ApplicationException, Thrift::TransportException], :exception_class_overrides=>[], :retries=>2, :server_retry_period=>0, :server_max_requests=>nil, :retry_overrides=>{}, :wrapped_exception_classes=>[Thrift::ApplicationException, Thrift::TransportException], :connect_timeout=>0.1, :timeout=>3, :timeout_overrides=>{}, :cached_connections=>false, :thrift_client_class=>ThriftClient}, @cached=false, @marked_down_til=2016-03-21 12:13:12 +0200, @connection=#, @rbuf="", @wbuf="", @read=true, @write=true, @index=0>, @transport_wrapper=Thrift::FramedTransport, @server="127.0.0.1:9160", @timeout=0.1>, @client=nil>]. (ThriftClient::NoServersAvailable)
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/thrift_client-0.8.4/lib/thrift_client/abstract_thrift_client.rb:219:in no_servers_available!'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/thrift_client-0.8.4/lib/thrift_client/abstract_thrift_client.rb:105:in
rescue in connect!'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/thrift_client-0.8.4/lib/thrift_client/abstract_thrift_client.rb:96:in connect!'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/thrift_client-0.8.4/lib/thrift_client/abstract_thrift_client.rb:159:in
handled_proxy'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/thrift_client-0.8.4/lib/thrift_client/abstract_thrift_client.rb:53:in login'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/cassandra-0.23.0/lib/cassandra/cassandra.rb:124:in
login!'
/home/tk/WorkSpaceNew/server-new/lib/cassandra_connection_provider.rb:47:in connect_to_cassandra'
/home/tk/WorkSpaceNew/server-new/lib/cassandra_connection_provider.rb:4:in
connection'
/home/tk/WorkSpaceNew/server-new/config/initializers/cassandra.rb:1:in <top (required)>'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in
load'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in block in load'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:213:in
load_dependency'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in load'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/engine.rb:609:in
block (2 levels) in '
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/engine.rb:608:in each'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/engine.rb:608:in
block in '
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/initializable.rb:30:in instance_exec'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/initializable.rb:30:in
run'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/initializable.rb:55:in block in run_initializers'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:150:in
block in tsort_each'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:183:in block (2 levels) in each_strongly_connected_component'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:210:in
block (2 levels) in each_strongly_connected_component_from'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:219:in each_strongly_connected_component_from'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:209:in
block in each_strongly_connected_component_from'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/initializable.rb:44:in each'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/initializable.rb:44:in
tsort_each_child'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:203:in each_strongly_connected_component_from'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:182:in
block in each_strongly_connected_component'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:180:in each'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:180:in
each_strongly_connected_component'
/home/tk/.rvm/rubies/ruby-2.0.0-p353/lib/ruby/2.0.0/tsort.rb:148:in tsort_each'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/initializable.rb:54:in
run_initializers'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/application.rb:215:in initialize!'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/railties-4.0.0/lib/rails/railtie/configurable.rb:30:in
method_missing'
/home/tk/WorkSpaceNew/server-new/config/environment.rb:8:in <top (required)>' config.ru:3:inrequire' config.ru:3:in block in <main>'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.4/lib/rack/builder.rb:55:in
instance_eval'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/rack-1.5.4/lib/rack/builder.rb:55:in initialize' config.ru:1:innew' config.ru:1:in <main>'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/passenger-5.0.26/src/helper-scripts/rack-preloader.rb:110:in
eval'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/passenger-5.0.26/src/helper-scripts/rack-preloader.rb:110:in preload_app'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/passenger-5.0.26/src/helper-scripts/rack-preloader.rb:156:in
'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/passenger-5.0.26/src/helper-scripts/rack-preloader.rb:30:in <module:PhusionPassenger>'
/home/tk/.rvm/gems/ruby-2.0.0-p353/gems/passenger-5.0.26/src/helper-scripts/rack-preloader.rb:29:in
' Error ID 5f40a8bc

I don't know why it is happens and how to fix it. Help me pls.

Regular expression error in veryfing xml against xsd

I'm making verification xml against xsd and every regular expressions in xsd works well, except from that one:
'{http://ift.tt/1WBVvaA', attribute 'EmailPodmiotu': [facet 'pattern'] The value 'testecs@huzar.pl' is not accepted by the pattern '[A-Za-z0-9]+((\.|-|_)[A-Za-z0-9]+)*(@[A-Za-z0-9]+((\.|-|_)[A-Za-z0-9]+)*){1}'.'

Can someone tell me if this expression is wrong or i can add some functionality to my app?

Parse the xml from remote link using happymapper gem

I am trying to parse the remote link which contains xml data to show it on my website. But the happy mapper gem returns empty array in response. I have the following code in my lib.

module XmlParser
 class BlogFeeds
  include HappyMapper

  element :title, String

  def self.fetch_feeds
    xml_response = HTTParty.get("http://ift.tt/1pWfnux").body
    feeds = BlogFeeds.parse(xml_response)
    feeds.each do |feed|
      puts feed.title
    end
  end
 end
end

Can anyone help in this regards.

How to implement a collection level lock in mongodb?

I am using mongodb with rails app and have model post.rb

If i am going to destroy a record of post, I want to have collection level lock so that the user wont be able to fire the destroy request twice for the same record and its before_destroy callback will not get executed twice.

Rails save contact details to another table

In my rails app, during checkout, the user contact details are pulled from user profile by default, but if for example the phone_number is empty in profile table, the field will be left empty. Once checkout if the user change or maintain the data, the data will be saved to contact_details table and user will be redirect to PayPal, in case user cancel the payment in PayPal, they will return back to checkout page and existing data are pulled from previously saved contact_details table.

Now the issues is, how can I can display user profile in the fields, but save the data to contact_details? Following were my code

        <%= form_for(@invoice) do |f| %>
            <div class="form-block">
              <div class="form-group col-md-6 firstname">
                <label for="sec">First Name:</label>
                <input type="text" placeholder='First Name' class="form-control input-pay" id="sec" name="contact_detail[first_name]" value="<%= @current_user.profile.first_name %>">
              </div>

    <div class="form-group col-md-6 firstname">
        <label for="sec">Email:</label>
        <input type="text" placeholder='Email' class="form-control input-pay" id="sec" name="contact_detail[email]" value="<%= @current_user.email %>">
     </div>

    </div>
<% end %>

controller:

def new

        @invoice = Invoice.new
        if request.post?

            @invoice.booking_date = params[:datepicker]
            @invoice.product_id = params["product-id"]
            @invoice.variants = params[:variant]
            if !user_signed_in?
                session[:pending_invoice] = @invoice
                return redirect_to new_user_session_path
            end

            set_extra_params_for_new

            @invoice_params = {}
            @contact_detail_params = {}

        else

            if (session[:pending_invoice].present?) && (session[:pending_invoice].instance_of? Invoice)

                @invoice = session[:pending_invoice]
                set_extra_params_for_new

                @invoice_params = {}
                @contact_detail_params = {}
                session[:pending_invoice] = nil
            else
                @invoice.booking_date = params[:invoice][:booking_date]
                @invoice.product_id = params[:invoice][:product_id]
                @invoice.coupon_id = params[:invoice][:coupon_id]
                @invoice.coupon_amounts = params[:invoice][:coupon_amounts]
                @coupon_amounts_with_user_currency = params[:invoice][:coupon_amounts_with_user_currency]
                @invoice.variants = params[:variant]

                set_extra_params_for_new

                @invoice_params = params[:invoice]
                @contact_detail_params = params[:contact_detail]
            end
        end

        set_invoice_currency_attributes(@invoice)

        gon.invoice = @invoice
        gon.real_total_with_currency = @invoice.real_total_with_currency
        gon.real_total = @invoice.real_total

    end

private



        def contact_detail_params
            params.require(:contact_detail).permit(:first_name, :last_name, :email, :phone_number, :message)
        end

dimanche 20 mars 2016

Why is Solr being used in my Rails app? How do I strip it out?

I don't want Solr being used in my development/test environment. It's causing too many complications. How do I strip it out?

This is what happens when I create a model using FactoryGirl:

[ path=#<RSolr::Client:0x007fe93a612aa8> parameters={data: <?xml version="1.0" encoding="UTF-8"?><add><doc><field name="id">Story 718</field><field name="type">Story</field><field name="type">ActiveRecord::Base</field><field name="class_name">Story</field><field name="status_s">incomplete</field><field name="title_text">Pizza For Dummies</field><field name="description_text">Are you dumb? Do you like pizza? Then this this is the story for you!</field></doc></add>, headers: {"Content-Type"=>"text/xml"}, method: post, params: {:wt=>:ruby}, query: wt=ruby, path: update, uri: http://localhost:8982/solr/collection1/update?wt=ruby, open_timeout: , read_timeout: , retry_503: , retry_after_limit: } ]

RSolr::Error::Http: RSolr::Error::Http - 404 Not Found
Error:     Not Found

I'd like to just bypass solr functionality in tests/development. How does one do this?

How to include prompt text in multiple places in select field with Rails 3.2

Is there a way to insert text that prompts users in my select field? i.e. my dropdown for the select might look like

Select your league

NFL

NHL

NBA

MLB

Alternate leagues

EPL

La Liga

Russian PL

Is this possible in Rails 3.2 I have this code which pulls my primary choices + secondary choices... I would like a prompt before the secondary choices.

f.select("league_id", @leagues.collect {|league| [ league.name, league.id ] } + [nil] + @worldwide_leagues.collect {|league| [ league.name, league.id ] })  

rspec test of index, show all not archived

Im trying to set up a (basic) test for a new feature I am going to implement. I have a job controller and instead of default showing all jobs I like to hide all the ones which is archived. I tried different ways but it seems like i am missing a piece or two of this puzzle. First i tried with calling 'visit' but get the message it does not exist. Second approach is using 'render' but that also ends up in a error saying render does not exists. (can i even use these methods in a controller spec?)

Is it wrong to put this in a controller test?

2 last test are causing errors

require "rails_helper"
require "spec_helper"


describe JobsController, :type => :controller do 

  context 'GET index' do   
   it "should be successful" do
     get :index
     expect(response).to be_success
   end

  it "renders the index template" do
   get :index
   expect(response).to render_template("index")
 end

 it "should not show any archived jobs as default" do
    visit jobs_path
    page.should have_no_content("Archived")

 end

  it 'should show the headers' do
    render :template => 'job/index', :layout => 'layouts/job'
    rendered.should_not contain('Archived')

  end

 end
end

how to manage users by an admin in ruby on rails

how can I manage and edit other users profiles as an admin since I have one model and controller (users) ?

I tried to add a new action called updateusers

def updateusers
    @other_user=User.find(params[:id])
    if @other_user.update_attributes(otherusers_params) 
            redirect_to '/' 
    else
            redirect_to '/manage'
   end
end 

the problem here :it is updating my admin user with the other_user's data

stack trace

    Started GET "/manage" for ::1 at 2016-03-19 21:06:08 +0300 Processing by
     UsersController#manage as HTML User Load (1.0ms) SELECT "users".* FROM 
"users" Rendered users/manage.html.erb within layouts/application (5.0ms) User 
Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 
[["id", 1]] Completed 200 OK in 53ms (Views: 51.0ms | ActiveRecord: 1.0ms)


    'Started GET "/users/10" for ::1 at 2016-03-19 21:06:10 +0300 Processing by 
UsersController#show as HTML Parameters: {"id"=>"10"} User Load (0.0ms) SELECT 
"users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 10]] Rendered 
users/show.html.erb within layouts/application (0.0ms) User Load (0.0ms) SELECT 
"users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Completed 200 
OK in 37ms (Views: 36.0ms | ActiveRecord: 0.0ms)


    Started GET "/editusers/10" for ::1 at 2016-03-19 21:06:11 +0300 Processing 
by UsersController#editusers as HTML Parameters: {"id"=>"10"} User Load (0.0ms) 
SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 10]] 
Rendered users/editusers.html.erb within layouts/application (4.0ms) User Load 
(1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]] 
Completed 200 OK in 41ms (Views: 39.0ms | ActiveRecord: 1.0ms)


    Started PATCH "/users/10" for ::1 at 2016-03-19 21:06:15 +0300 Processing by 
UsersController#update as HTML Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"6M1TGLQUEhiezCCg9/rT5IofdroMiQ0sm+bYcihgGDxTjDdFGU2Riou2p‌​
cRk5ncjCtFDGwfBj17Uq7gc0u329w==", "user"=>{"first_name"=>"g", "last_name"=>"g", 
"email"=>"g@g.g", "role"=>"editor", "image"=>"pic.png", "admins"=>""}, 
"other"=>"update", "id"=>"10"} User Load (0.0ms) SELECT "users".* FROM "users" 
WHERE "users"."id" = ? LIMIT 1 [["id", 1]] Unpermitted parameters: role, admins


    (0.0ms) begin transaction SQL (1.0ms) UPDATE "users" SET "first_name" = ?, 
"last_name" = ?, "email" = ?, "updated_at" = ? WHERE "users"."id" = ? 
[["first_name", "g"], ["last_name", "g"], ["email", "g@g.g"], ["updated_at", 
"2016-03-19 18:06:15.488284"], ["id", 1]] (47.0ms) commit transaction Redirected 
to localhost:8080/profile Completed 302 Found in 54ms (ActiveRecord: 48.0ms)

samedi 19 mars 2016

catch params of check box pagination using jquery datable gem

unable to catch check_box params of remaining pages i am getting only 1st page params please help me

I am able to catch only submit page params

my view

 <table id="associations" class="table table-striped table-bordered ">
      <thead>
      <th>Check</th>
      <th>Logo</th>
      </thead>
      <tbody>
      <% @benefits.each do |benefit|%>
          <%@selected_benefits = AssocBenefit.where(:benefit_id=>benefit.id, :association_id => @association.id, :status => true).first%>
          <tr>
            <td>
              <%#= check_box_tag :car, :value => 2, :checked => (f.sex == 2) %>
              <%if @selected_benefits.present?%>
                  <%= hidden_field_tag 'benefits1[]', benefit.id %>
                  <%= check_box_tag 'benefits[]', benefit.id, :checked => (benefit.id == @selected_benefits.id)%>
                  </td>
              <%else%>
                  <%= hidden_field_tag 'benefits1[]', benefit.id %>
                  <%= check_box_tag 'benefits[]', benefit.id%></td>
              <%end%>
              <td><%= image_tag benefit.image(:thumb) %></td>
              <td><%= benefit.benefits_name%></td>

      <%end%>
      </tbody>
    </table> 

My controller

        def save_choose_benefits
   assoc_benefits = AssocBenefit.where.not(:benefit_id =>  params[:benefits]).all if params[:benefits1]
      assoc_benefits.delete_all
       unless params[:benefits].blank?

    params[:benefits].each do |d|
    ss= AssocBenefit.where(:benefit_id => d).first
    if ss.blank?
         assoc_benefits = AssocBenefit.new(:benefit_id => d ,:association_id => params[:association_id], :status=>"true")
      if assoc_benefits.valid?
        assoc_benefits.save
      end
      end
     end
      end
redirect_to associations_list_path ,:notice => "Successfully applied"

 end

here is my script

       <script>
    $(document).ready(function()
       {
           $('#associations').dataTable();
       }
      );
    </script>

I installed gem jquery-datatables and also jquery-turbolink to pass params but there is no luck to pass params of second page and etc..

please help me out of these solution

thanks

How to show controller or model with all decorators applied from gems?

Is there a way to show the complete decorated controller/model in one file? For example, I have a controller that is being decorated with many gems I've installed and I would like to see the complete finished code in one view.

vendredi 18 mars 2016

When to execute Rails after commit

If I have a concern like this:

module SomeModule
  extend ActiveSupport::Concern

  included do
    after_commit :execute, on: WHEN_TO_EXECUTE
  end
end

Is it possible to specify a constant on the included classes WHEN_TO_EXECUTE in which it holds a symbol of whatever :update, :create?

I it is not possible to make the after_commit dynamic like this with any other way?

Closest div as container for bootstrap datepicker in rails and coffee script and simple_form

I am trying to set up bootstrap datepicker in my rails application.

It is working fine but the css is all messed up unless i assign a container div that can hold the pop up.

I would like to make a generic method that checks the closest div for the popup instead of appending it to the body.

Here is my code

Coffee

jQuery ->
jQuery('input.date_picker').datepicker
    dateFormat: 'mm/dd/yyyy'
    todayHighlight: true
    container: jQuery(this).closest('div').attr(class)
    autoclose: true
    todayBtn: true

Erb

    <%= simple_form_for @qc_assay_parameter, :url => qc_assay_parameter_path(@qc_assay_parameter) do |f| %>
     <%= f.error_messages %>
     <%= f.input :reference_number, label: 'Reference #', error: 'Reference Number is mandatory' %>
     <%= f.input :qc_assay_product_name_with_revision, label: 'Analyte , Rev#', url: '/qc_revisions', as: :autocomplete, placeholder: 'Type in Analyte Name', :input_html => {:class =>"span2", :rows => 6, :type => :text}%>
     <%= f.input :assay_date, as: :date_picker, placeholder: 'mm/dd/yyyy' %>
    <%= f.button :submit %>
   <%end%>

Plain Html

 <form id="edit_qc_assay_parameter_176094" class="simple_form edit_qc_assay_parameter" novalidate="novalidate" method="post" action="/qc_assay_parameter.176094" accept-charset="UTF-8">
<div style="margin:0;padding:0;display:inline">
<div class="input string required qc_assay_parameter_reference_number">
<div class="input autocomplete optional qc_assay_parameter_qc_assay_product_name_with_revision">
<label class="autocomplete optional control-label" for="qc_assay_parameter_qc_assay_product_name_with_revision">Analyte , Rev#</label>
<span class="ui-helper-hidden-accessible" role="status" aria-live="polite"></span>
<input id="qc_assay_parameter_qc_assay_product_name_with_revision" class="autocomplete optional span2 ui-autocomplete-input" type="text" value="LAP revision 0" size="30" rows="6" placeholder="Type in Analyte Name" name="qc_assay_parameter[qc_assay_product_name_with_revision]" data-autocomplete="/qc_revisions" autocomplete="off">
</div>
<div class="input date_picker optional qc_assay_parameter_assay_date">
<label class="date_picker optional control-label" for="qc_assay_parameter_assay_date">Assay date</label>
<input id="qc_assay_parameter_assay_date" class="string date_picker optional datepicker" type="date_picker" value="Sun, 03 Apr 2016 00:00:00 -0500" size="30" placeholder="mm/dd/yyyy" name="qc_assay_parameter[assay_date]">
</div>
<input class="btn" type="submit" value="Update Qc assay parameter" name="commit">
</form>

I would like to do something like

jQuery ->
jQuery('input.date_picker').datepicker
    dateFormat: 'mm/dd/yyyy'
    todayHighlight: true
    container: jQuery(this).closest('div').attr(class)
    autoclose: true
    todayBtn: true

container: jQuery(this).closest('div')

Escape encoding of liquid tags in Nokogiri

We are using Nokogiri gem and the html we get from the test editor is saved using Nokogiri Nokogiri::HTML::fragment(html_text).to_html converts into proper html tags and is getting saved to the database. But we are having some liquid tags which when rendered substitutes the value in the place where tags are added.

eg. html code snippet

<body>
  <div>
    <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit.Dolorem quam itaque, dolore esse labore dolorum inventore optio earum iure explicabo impedit eveniet perspiciatis nobis vero culpa aliquid, iusto saepe sunt.</p>
    <a href="http://some_link">{{some_link}}</a>
    <div>
      <a href="{{payment_link}}">{{payment_link}}</a>
    </div>
  </div>
</body>

once we convert it into the html tags using nokogiri it gets text in the url gets encoded(href="{{payment_link}}"). Is there a way to escape url encoding for the liquid tags?

This is how the html code when rendered and saved looks like in db

Output data

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do  eiusmod<br>\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,<br>\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo<br>\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse<br>\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non<br>\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n\n<p> </p>\n\n<p><a href=\"http://%7B%7Bpayment_link%7D%7D\">{{payment_link}}</a></p>"

Expected data

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do  eiusmod<br>\ntempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,<br>\nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo<br>\nconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse<br>\ncillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non<br>\nproident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>\n\n<p> </p>\n\n<p><a href=\"{{payment_link}}">{{payment_link}}</a></p>

Feed the html generated by erb's to the react.render method

I am trying to render the html generated by the erb's (embedded ruby) throught the react.render method. Can we use the erb's to feed the html generated by them to the react.render method? E.g. can I somehow inject this piece of code, for pagination by kaminari gem <%= paginate admins, :remote => true %> to some react class like below?

#app/assets/javascripts/components/adminerror.js.coffee.erb
@AdminError = React.createClass

  getDefaultProps: ->
    errorText: ""

  render: ->
    dom.div
      className: 'help-block has-error'
      @props.errorText
      <%= paginate @state.admins, :remote => true %>

DRY Rails controller to avoid repeating multiple times same method

I would like to DRY my controller as I use some snippets/blocks of code many times inside the same controller (I have removed some as it was too long but this already gives an idea of the repetition). Here are the blocks I keep repeating :

  • @deal = search_deal

  • @next_deal = find_next_deal

  • @userdeal = find_or_create_userdeal_participation

  • @user_credits = calculate_user_credits_in_deal

I'm quite rookie and don't know how to do this but I feel this code should be factorized.

class DealsController < ApplicationController

  before_filter :find_deal,
    :only => [  :showcase ]
  before_filter :ensure_canonical_deal_path!,
    :only => [  :showcase ]   

  def showcase    
    # find appropriate deal
    @deal = search_deal 

    respond_to do |format|
      format.html # showcase.html.erb
      format.json { render json: @deal }
    end      

  end  

  def buy_stuff
    @deal = search_deal 
    # bring 'next deal' url to the view
    @next_deal                   = find_next_deal

    # USER IS SIGNED-IN
    if user_signed_in?

      @userdeal                     = find_or_create_userdeal_participation
      @user_credits = calculate_user_credits_in_deal

      # if: user still has credits available
      if @user_credits >= 1 
        #do this
        respond_to do |format|
          format.js 
        end

      else
        respond_to do |format|
          # do that
        end
      end  

    # USER IS NOT SIGNED-IN 

    else  
      respond_to do |format|
        format.js { render :template => "deals/call_to_sign_in.js.erb" }
      end
    end
  end


  def show_discounts
    @deal = search_deal 
    respond_to do |format|
      #do that
    end
  end

  def pending_deals
    @deal = search_deal 
    # bring 'next deal' url to the view
    @next_deal                   = find_next_deal
    if user_signed_in?

      @userdeal                     = find_or_create_userdeal_participation
      @user_credits = calculate_user_credits_in_deal
    end

    respond_to do |format|
      #do this
    end
  end

  def ask_question
    @deal = search_deal 
    respond_to do |format|
      #do that
    end
  end


  protected  


    def ensure_canonical_deal_path!
      if request.path != actual_deal_page_path(@deal)
        redirect_to actual_deal_page_path(@deal, :format => params[:format]), :status => :moved_permanently
        return false
      end
    end



  private
    # DRY file as this is used multiple times 
    # trick source - http://ift.tt/1RowOjy
    def search_deal
      Deal.friendly.find(params[:id])
    end

    def find_or_create_userdeal_participation
      UserDeal.where('user_id = ? AND deal_id = ?', current_user.id, @deal.id).take ||
      UserDeal.create(user_id: current_user.id, deal_id: @deal.id)
    end

    def calculate_user_credits_in_deal
      current_user.credit_nb + @userdeal.history
    end

    def find_next_deal
      Deal.order_next_deal_at(@deal).next
    end

end

jeudi 17 mars 2016

Rails : Application Error An error occurred in the application

I build my app on local with postgres database,then it can normally run,but get this error message after publish in to Heroku....

Application Error
An error occurred in the application and your page could not be served. Please try again in a few moments.

If you are the application owner, check your logs for details.

Here is outputs from "heroku logs", please help, this is my first time on heroku...

2016-03-17T19:41:32.331650+00:00 app[web.1]:    from /app/config.ru:3:in `block in <main>'
2016-03-17T19:41:32.331657+00:00 app[web.1]:    from /app/config.ru:in `new'
2016-03-17T19:41:32.331658+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:40:in `parse_file'
2016-03-17T19:41:32.331643+00:00 app[web.1]:    from /app/config/environment.rb:5:in `<top (required)>'
2016-03-17T19:41:32.331650+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:55:in `instance_eval'
2016-03-17T19:41:32.331660+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:314:in `wrapped_app'
2016-03-17T19:41:32.331657+00:00 app[web.1]:    from /app/config.ru:in `<main>'
2016-03-17T19:41:32.331662+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/commands_tasks.rb:76:in `server'
2016-03-17T19:41:32.362958+00:00 app[web.1]: => Run `rails server -h` for more startup options
2016-03-17T19:41:32.362959+00:00 app[web.1]: => Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
2016-03-17T19:41:32.331658+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:49:in `new_from_string'
2016-03-17T19:41:32.331660+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:250:in `start'
2016-03-17T19:41:32.331659+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/server.rb:50:in `app'
2016-03-17T19:41:32.362960+00:00 app[web.1]: => Ctrl-C to shutdown server
2016-03-17T19:41:32.331659+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:277:in `build_app_and_options_from_config'
2016-03-17T19:41:32.331663+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands.rb:17:in `<top (required)>'
2016-03-17T19:41:32.331665+00:00 app[web.1]:    from bin/rails:4:in `<main>'
2016-03-17T19:41:32.331651+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:55:in `initialize'
2016-03-17T19:41:32.331660+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/server.rb:69:in `start'
2016-03-17T19:41:32.331662+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/commands_tasks.rb:76:in `tap'
2016-03-17T19:41:32.331664+00:00 app[web.1]:    from bin/rails:4:in `require'
2016-03-17T19:41:32.362942+00:00 app[web.1]: => Booting WEBrick
2016-03-17T19:41:32.331658+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:49:in `eval'
2016-03-17T19:41:32.331662+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/commands_tasks.rb:81:in `block in server'
2016-03-17T19:41:32.331663+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
2016-03-17T19:41:32.362957+00:00 app[web.1]: => Rails 4.1.8 application starting in production on http://0.0.0.0:29941
2016-03-17T19:41:32.362985+00:00 app[web.1]: Exiting
2016-03-17T19:41:33.216453+00:00 heroku[web.1]: State changed from starting to crashed
2016-03-17T19:41:33.217046+00:00 heroku[web.1]: State changed from crashed to starting
2016-03-17T19:41:33.205653+00:00 heroku[web.1]: Process exited with status 1
2016-03-17T19:41:36.884650+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 21998 -e production`
2016-03-17T19:41:42.845374+00:00 app[web.1]: /app/app/models/CarrierwaveImage.rb:2:in `<class:CarrierwaveImage>': uninitialized constant CarrierwaveImage::AssetUploader (NameError)
2016-03-17T19:41:42.845396+00:00 app[web.1]:    from /app/app/models/CarrierwaveImage.rb:1:in `<top (required)>'
2016-03-17T19:41:42.845402+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/engine.rb:468:in `block (2 levels) in eager_load!'
2016-03-17T19:41:42.845408+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/engine.rb:467:in `each'
2016-03-17T19:41:42.845415+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/engine.rb:467:in `block in eager_load!'
2016-03-17T19:41:42.845416+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/engine.rb:465:in `each'
2016-03-17T19:41:42.845416+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/engine.rb:465:in `eager_load!'
2016-03-17T19:41:42.845417+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/engine.rb:346:in `eager_load!'
2016-03-17T19:41:42.845417+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/application/finisher.rb:58:in `each'
2016-03-17T19:41:42.845418+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/initializable.rb:30:in `instance_exec'
2016-03-17T19:41:42.845418+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/application/finisher.rb:58:in `block in <module:Finisher>'
2016-03-17T19:41:42.845419+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/initializable.rb:30:in `run'
2016-03-17T19:41:42.845419+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/initializable.rb:55:in `block in run_initializers'
2016-03-17T19:41:42.845420+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'
2016-03-17T19:41:42.845420+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'
2016-03-17T19:41:42.845421+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'
2016-03-17T19:41:42.845421+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'
2016-03-17T19:41:42.845422+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `each'
2016-03-17T19:41:42.845422+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `call'
2016-03-17T19:41:42.845423+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'
2016-03-17T19:41:42.845423+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'
2016-03-17T19:41:42.845424+00:00 app[web.1]:    from /app/vendor/ruby-2.2.4/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'
2016-03-17T19:41:42.845427+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/initializable.rb:54:in `run_initializers'
2016-03-17T19:41:42.845428+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/application.rb:300:in `initialize!'
2016-03-17T19:41:42.845444+00:00 app[web.1]:    from /app/config.ru:3:in `block in <main>'
2016-03-17T19:41:42.845435+00:00 app[web.1]:    from /app/config/environment.rb:5:in `<top (required)>'
2016-03-17T19:41:42.845444+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:55:in `instance_eval'
2016-03-17T19:41:42.845445+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:55:in `initialize'
2016-03-17T19:41:42.845454+00:00 app[web.1]:    from /app/config.ru:in `new'
2016-03-17T19:41:42.845455+00:00 app[web.1]:    from /app/config.ru:in `<main>'
2016-03-17T19:41:42.845456+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:49:in `eval'
2016-03-17T19:41:42.845456+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:49:in `new_from_string'
2016-03-17T19:41:42.845456+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/builder.rb:40:in `parse_file'
2016-03-17T19:41:42.845457+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:277:in `build_app_and_options_from_config'
2016-03-17T19:41:42.845458+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:199:in `app'
2016-03-17T19:41:42.845458+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/server.rb:50:in `app'
2016-03-17T19:41:42.845459+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:314:in `wrapped_app'
2016-03-17T19:41:42.845459+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.5.5/lib/rack/server.rb:250:in `start'
2016-03-17T19:41:42.845460+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/server.rb:69:in `start'
2016-03-17T19:41:42.845460+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/commands_tasks.rb:81:in `block in server'
2016-03-17T19:41:42.845461+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/commands_tasks.rb:76:in `server'
2016-03-17T19:41:42.845461+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/commands_tasks.rb:76:in `tap'
2016-03-17T19:41:42.845462+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
2016-03-17T19:41:42.845463+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.1.8/lib/rails/commands.rb:17:in `<top (required)>'
2016-03-17T19:41:42.845463+00:00 app[web.1]:    from bin/rails:4:in `require'
2016-03-17T19:41:42.845464+00:00 app[web.1]:    from bin/rails:4:in `<main>'
2016-03-17T19:41:42.882058+00:00 app[web.1]: => Booting WEBrick
2016-03-17T19:41:42.882072+00:00 app[web.1]: => Rails 4.1.8 application starting in production on http://0.0.0.0:21998
2016-03-17T19:41:42.882073+00:00 app[web.1]: => Run `rails server -h` for more startup options
2016-03-17T19:41:42.882074+00:00 app[web.1]: => Notice: server is listening on all interfaces (0.0.0.0). Consider using 127.0.0.1 (--binding option)
2016-03-17T19:41:42.882075+00:00 app[web.1]: => Ctrl-C to shutdown server
2016-03-17T19:41:42.882076+00:00 app[web.1]: Exiting
2016-03-17T19:41:43.950847+00:00 heroku[web.1]: State changed from starting to crashed
2016-03-17T19:41:43.921917+00:00 heroku[web.1]: Process exited with status 1
2016-03-17T19:42:43.486656+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=seastalk.herokuapp.com request_id=525b321b-e0b2-4b3b-845b-e816884cfaf9 fwd="58.11.231.116,58.11.231.116" dyno= connect= service= status=503 bytes=
2016-03-17T19:42:44.932789+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=seastalk.herokuapp.com request_id=7feaed6b-95d7-4bac-859f-57981a5d6b21 fwd="58.11.231.116" dyno= connect= service= status=503 bytes=
2016-03-17T19:43:01.807436+00:00 heroku[api]: Starting process with command `bundle exec rake db:create` by tanapon.aree@gmail.com
2016-03-17T19:43:06.234302+00:00 heroku[run.7837]: Starting process with command `bundle exec rake db:create`
2016-03-17T19:43:06.199601+00:00 heroku[run.7837]: Awaiting client
2016-03-17T19:43:06.528081+00:00 heroku[run.7837]: State changed from starting to up
2016-03-17T19:43:10.186725+00:00 heroku[run.7837]: State changed from up to complete
2016-03-17T19:43:10.171105+00:00 heroku[run.7837]: Process exited with status 0
2016-03-17T19:44:07.685116+00:00 heroku[api]: Starting process with command `bundle exec rake db:migrate` by tanapon.aree@gmail.com
2016-03-17T19:44:12.203361+00:00 heroku[run.1435]: Starting process with command `bundle exec rake db:migrate`
2016-03-17T19:44:12.171575+00:00 heroku[run.1435]: Awaiting client
2016-03-17T19:44:12.589482+00:00 heroku[run.1435]: State changed from starting to up
2016-03-17T19:44:15.993241+00:00 heroku[run.1435]: Process exited with status 0
2016-03-17T19:44:16.005134+00:00 heroku[run.1435]: State changed from up to complete
2016-03-17T19:45:24.867558+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=seastalk.herokuapp.com request_id=537623dd-038d-46ee-865a-05e0aabd4974 fwd="58.11.231.116,58.11.231.116" dyno= connect= service= status=503 bytes=
2016-03-17T19:45:26.326734+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=seastalk.herokuapp.com request_id=aaaf0876-a326-44f3-9c8f-698e7b7d8768 fwd="58.11.231.116" dyno= connect= service= status=503 bytes=