dimanche 30 avril 2017

image uploading error ruby on rails

I am getting the two errors, shown in the image below, when I try to upload an image using carrierwave. The image field goes blank every time I try to upload an image. I am new to ruby on rails and am looking for anything that will help.

enter image description here

post_controller.rb

  # GET /posts/new
def new
  @post = Post.new
end

# POST /posts
# POST /posts.json
def create
  @post = Post.new(post_params)

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

create_posts.rb (the model file)

class CreatePosts < ActiveRecord::Migration[5.0]
  def change
    create_table :posts do |t|
      t.string :title
      t.string :image
      t.text :description

      t.timestamps null:false
   end
 end
end

_form.html.erb (the view file)

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

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

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

<div class="field">
  <%= f.label :image %>
  <%= f.file_field :image %>
</div>

<div class="field">
  <%= f.label :description %>
  <%= f.text_area :description %>
</div>

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

samedi 29 avril 2017

DEVISE sign in not working

Hi I'm very new to rails so I'm not sure what I'm doing wrong. I'm working on an app and have implemented very basic devise. The console output indicates that it should move on to the the page in the path when a sign is complete but it is never getting passed the sign in page.

User.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :sessions, dependent: :destroy
  has_many :session2s, dependent: :destroy
end

routes.rb

Rails.application.routes.draw do
# resources :users
devise_for :users
resources :sessions do 
  resources :session2s 
end
# The priority is based upon order of creation: first created -> highest    priority.
# See how all your routes lay out with "rake routes".

# You can have the root of your site routed with "root"
root 'application#index'
get '/welcome'=>'application#index'
post'/sessions/user'=>'sessions#new'

rake routes

new_user_session GET    /users/sign_in(.:format)                           devise/sessions#new
        user_session POST   /users/sign_in(.:format)                           devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format)                          devise/sessions#destroy
   new_user_password GET    /users/password/new(.:format)                      devise/passwords#new
  edit_user_password GET    /users/password/edit(.:format)                     devise/passwords#edit
       user_password PATCH  /users/password(.:format)                          devise/passwords#update
                     PUT    /users/password(.:format)                          devise/passwords#update
                     POST   /users/password(.:format)                          devise/passwords#create
cancel_user_registration GET    /users/cancel(.:format)                            devise/registrations#cancel
   new_user_registration GET    /users/sign_up(.:format)                           devise/registrations#new
   edit_user_registration GET    /users/edit(.:format)                              devise/registrations#edit
       user_registration PATCH  /users(.:format)                                   devise/registrations#update
                         PUT    /users(.:format)                                   devise/registrations#update
                         DELETE /users(.:format)                                   devise/registrations#destroy
                     POST   /users(.:format)                                   devise/registrations#create
   session_session2s GET    /sessions/:session_id/session2s(.:format)          session2s#index
                     POST   /sessions/:session_id/session2s(.:format)          session2s#create
new_session_session2 GET    /sessions/:session_id/session2s/new(.:format)      session2s#new
   edit_session_session2 GET    /sessions/:session_id/session2s/:id/edit(.:format) session2s#edit
        session_session2 GET    /sessions/:session_id/session2s/:id(.:format)      session2s#show
                     PATCH  /sessions/:session_id/session2s/:id(.:format)      session2s#update
                     PUT    /sessions/:session_id/session2s/:id(.:format)      session2s#update
                     DELETE /sessions/:session_id/session2s/:id(.:format)      session2s#destroy
            sessions GET    /sessions(.:format)                                sessions#index
                     POST   /sessions(.:format)                                sessions#create
new_session GET    /sessions/new(.:format)                            sessions#new
        edit_session GET    /sessions/:id/edit(.:format)                       sessions#edit
             session GET    /sessions/:id(.:format)                            sessions#show
                     PATCH  /sessions/:id(.:format)                            sessions#update
                     PUT    /sessions/:id(.:format)                            sessions#update
                     DELETE /sessions/:id(.:format)                            sessions#destroy
                root GET    /                                                  application#index
             welcome GET    /welcome(.:format)                                 application#index
       sessions_user POST   /sessions/user(.:format)                           sessions#new

console messages

Started POST "/sessions/user" for 107.15.244.73 at 2017-04-30 03:24:53 +0000
Cannot render console from 107.15.244.73! Allowed networks: 127.0.0.1, ::1,    127.0.0.0/127.255.255.255
Processing by SessionsController#new as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"A8ZTEKOg+86FHiL7HMUo69Cz+0OmYiedg92Nci3D/ZhWwK1W1WN7weI/gZtq9Qc0yC1igj/ZpPwtLm6YkJhY9Q==", "user"=>{"email"=>"z@g", "password"=>"[FILTERED]", "remember_me"=>"1"}, "commit"=>"Log in"}
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)


Started GET "/users/sign_in" for 107.15.244.73 at 2017-04-30 03:24:53 +0000
Cannot render console from 107.15.244.73! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by Devise::SessionsController#new as HTML
Rendering devise/sessions/new.html.erb within layouts/application
Rendered devise/shared/_links.html.erb (1.1ms)
Rendered devise/sessions/new.html.erb within layouts/application (4.2ms)
Completed 200 OK in 26ms (Views: 25.1ms | ActiveRecord: 0.0ms)

I just created the username and password in signup and the logs show its definitely entered into the table so I'm not sure what's happening. I see the 401 error but all the previous questions on this topic have more complicated devise methods so I'm not sure whats going and help on getting a functioning sign in page would be great ! Thanks!

vendredi 28 avril 2017

error while executing ruby's project

i am working in a ruby on rails , i have an error while displaying data. this is the erroe : undefined methodempty?' for nil:NilClasscode source erroe :-unless @history_derogations.empty? -@history_derogations.each do |item| tr td width="110px" =item.number td width="110px" =item.au_arrival_date td width="110px"`

How to run multiple RAILS versions for a SINGLE website / project

I've inherited a RAILS 3.2 production environment which is 'humming' away nicely.

The client now wants another major piece of work doing but I want to do it in RAILS 5. The web address would be the same for both the old site and the new project. The new project would be additional functionality which would be accessed via the old site.

Any one know of a way of keeping the old site running whilst I develop and MORE IMPORTANTLY deliver the new work via RAILS 5. Eventually if this all works then I get the opportunity to migrate the old site to RAILS 5. However for the moment I need to serve up both RAILS 3.2 AND RAILS 5 from the same site.

All help/advice gratefully accepted with thanks

Rails: Given a mailer view, how can I find its corresponding mailer action?

I want to find the action mailer corresponding to a specific mailer view. It seems that there are no mailer action with the name of the mailer view's name. How can I find the mailer action in this case?

p.s I am working on Rails code not written by me.

jeudi 27 avril 2017

uninitialized constant Rails::Server (NameError)

Currently while trying to set up my ruby files, i am running into this problem. Im not sure what the problem is, as Rails is correctly installed. I am mostly new to Rails/Ruby, and am picking up rails. I haven't seen this problem else where.

I am working on windows 10, all gems are installed, and rails is installed. Im am running this in RubyMine.

Here is the line where the error is thrown:

config.action_mailer.asset_host = 'http://localhost:' + Rails::Server.new.options[:Port].to_s

Here is an image of the console Console

How to check of section exists in IniParse.parse using Ruby?

require 'iniparse'

conf = IniParse.parse(File.read('my.conf'))

how do I check if conf['DEFAULT'] exist before reading it?

mercredi 26 avril 2017

Rails: For API's what should I write unit/functional/integration test cases?

I have rails microservices application for which I would like to write test cases, I would like to have suggestions

  1. For API what are the possible type test cases available?
  2. what type of test cases should I write functional/unit/integration?
  3. What is the difference in functional/unit/integration if we talk about it in the context of API's?

Ruby on Rails update method is accidentally called.. why?

I'm still new to Ruby on Rails and I am stucking at one Point.

My Database contains a Teacher and a Course model. They are associated with a has_and_belongs_to_many Association (at the moment it shouldn't be changed).

Course Detail View:

<p> Teacher:
    <%= form_tag url_for(controller: 'courses', action: 'add_teacher') ,method: 'put' do%>
    <%= select_tag :teacher, options_for_select(Teacher.all.collect {|t| [t._name, t.id]})%>
    <%= hidden_field_tag(:course, value = @course.id) %>
    <%= submit_tag 'hinzufügen' %>
    <%end %>
<% end %></p>

Course_Controller:

def add_teacher
    @course = Course.find(params[:course])
    @teacher = Teacher.find(params[:teacher]) unless params[:teacher].nil?
    @course.teachers << @teacher
    redirect_to action: 'show'
end


def update
    redirect_to action: 'add_teacher', course: params[:course], teacher: params[:teacher]
end

That was a part of my code. I don't really know if there is a routing problem or something else. I just don't get the point why the function update is called before the function add_teacher is called. First I thought maybe rails realized that I would like to change a existing record, so the function "update" is called when the change (@course.teachers << @teacher) "is happening" . But he first calls the update function and it doesn't matter if I redirect to add_teacher or not, he would call the function anyway! why?

Now i'm using the update function to redirect to add_teacher with the correct params. May someone has a better solution for me or an answer why the function 'update' is called automatically and how to set the routes correctly?

Thanks a lot for help and sorry for my bad english!

Bye

Can't retrieve access_token, refresh_token from Omniauth authentication strategy with Devise, Rails 4

I am using such gems:

gem "omniauth-yandex"
gem 'devise'

My setup.

Routes:

 devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }

Devise initializer:

config.omniauth :yandex, Rails.application.secrets.client_id , Rails.application.secrets.password, callback_url: "http://ift.tt/2pm5Akz"

User model:

devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:yandex]


   def self.from_omniauth(auth) 

      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.email =  auth.info.email
        user.password = Devise.friendly_token[0,20]
      end

  end

CallbackController:

class CallbacksController < Devise::OmniauthCallbacksController        

    def yandex
       #empty
    end
end

View:

  <%= link_to "Sign in with Yandex", user_yandex_omniauth_authorize_path, id: "sign_in" %>

When I click "Sign in with Yandex" my application prompts for user permission and then redirects back to my application. User is created in my database with such fields-- e-mail,provider, uid. But I would like to have also access_token, refresh_token and expires_at because I am using few Yandex API's.

When I httlog'ed above action (From clicking "Sign in .." to the redirect back to my application) I received these results:

D, [2017-04-26T19:17:42.091838 #24865] DEBUG -- : [0;30;101m[httplog] Connecting: oauth.yandex.ru:443[0m
D, [2017-04-26T19:17:42.266645 #24865] DEBUG -- : [0;30;101m[httplog] Sending: POST http://ift.tt/2qf9V6k
D, [2017-04-26T19:17:42.267040 #24865] DEBUG -- : [0;30;101m[httplog] Data: client_id=097253682f9f41289ec5exxxxxxx&client_secret=xxxxxxdb4fxx0eadcbb8a4143&code=xxxxx327&grant_type=authorization_code&redirect_uri=http%3A%2F%2Fcb2bcdc4.ngrok.io%2Fusers%2Fauth%2Fyandex%2Fcallback%3Fstate%xxxxxxxxxxx%26code%xxxx[0m
D, [2017-04-26T19:17:42.410712 #24865] DEBUG -- : [0;30;101m[httplog] Status: 200[0m
D, [2017-04-26T19:17:42.410945 #24865] DEBUG -- : [0;30;101m[httplog] Benchmark: 0.143445 seconds[0m
D, [2017-04-26T19:17:42.411168 #24865] DEBUG -- : [0;30;101m[httplog] Response:
{"token_type": "bearer", "access_token": "xxxxxxxxuyBwtcyAFjkBZo3F3MCiIaTI", "expires_in": 31528753, "refresh_token": "xxxxxxxxxxxClSH:Pts0u-Mfls-vdEc7-zTOod9ZWzegNFRxxxxxxxxxxxxxKHpwsqBFUHHKtg"}[0m
D, [2017-04-26T19:17:42.414748 #24865] DEBUG -- : [0;30;101m[httplog] Connecting: login.yandex.ru:443[0m
D, [2017-04-26T19:17:42.609376 #24865] DEBUG -- : [0;30;101m[httplog] Sending: GET http://ift.tt/2pmgkzw
D, [2017-04-26T19:17:42.609720 #24865] DEBUG -- : [0;30;101m[httplog] Data: [0m
D, [2017-04-26T19:17:42.675702 #24865] DEBUG -- : [0;30;101m[httplog] Status: 200[0m
D, [2017-04-26T19:17:42.675972 #24865] DEBUG -- : [0;30;101m[httplog] Benchmark: 0.065791 seconds[0m
D, [2017-04-26T19:17:42.676211 #24865] DEBUG -- : [0;30;101m[httplog] Response:
{"first_name": "xxxxxxxxxxx9", "last_name": "xxxxxxxxxxxxxxx", "display_name": "xxxxx", "emails": ["xxxxxx@yandex.ru"], "default_email": "xxxxx@yandex.ru", "real_name": "xxxxxx2", "login": "xxxxxxx", "sex": "male", "id": "xxxx123"}[0m

Question: How can I save access_token, refresh token from Omniauth authentication process to user as it is clearly visible (7th line ) that it does retrieve it using my client_id and secret without any of my code.

Thanks.

What I have tried:

Added user.access_token = auth.credentials.token to self.from_omniauth(auth) method in user model. But there wasn't any positive change.

mardi 25 avril 2017

how to use radio_button like check_box

hello everyone i have this code

 =form_tag products_path, method: :get, remote: true, id: "products_search" do
    =check_box_tag :search, "Bebes"

the above code is to search a product and works fine i get the event with JS to show the products with string "Bebes"

$('input[type=checkbox]').change () ->
  $.get $('#products_search').attr('action'), $('#products_search').serialize(), null, 'script'
  false

But i wanna use radio_button

i have this code:

=radio_button(:search, "search", "Bebes")

JS

$('input[type=radiobutton]').change () ->
  $.get $('#products_search').attr('action'), $('#products_search').serialize(), null, 'script'
  false

with the above code doesn't happen anything, someone can help me? i tried with this documentation http://ift.tt/2oul3jw but the param "search" is not a attribute of the Product model so i dont know how to do it :(

Javascript in Ruby on Rails

I have a small doubt. Can anyone explain me how to include javascript in rails app and my code is a sidebar toggler in my website.

Mycode:

 $("#menu-toggle").click( function (e){
     e.preventDefault();
       $("#wrapper").toggleClass("menuDisplayed"); 
   });

Description: menu toggle is my icon, which gives a menu with items in it , when I click on it and wrapper is the place where my menu resides. I want this code to work in Rails app.

1) can anyone tell me how to change this code in rails appa and how to work it in it.

2) If there is a better code than this for javascript toggler button function, can you tell me the code in javascript and even in rails app.

Thanks in advance.

Rails save a object inside a method

I have a method Order that if the status is completed decrease the product quantity on the method save and create a transaction record.

Everything works fine except that in the logs shows:

even showing the code still works

Someone please can explain why this happen?

def order_sold

    if sold
         order = Order.find(params[:id])
       product = order.product

      if order
        if params[:status] == 'COMPLETED'
          order.status = Order.statuses[0]
          product = order.product
          quantity = product.quantity
          product.quantity -= order.quantity
          product.save
          transaction = Transaction.new
          transaction.user_id = order.buyer_id
          transaction.status = params[:status]
          order.transaction = transaction
          order.save
          OrderMailer.order_confirmation(order).deliver


        end
      end


    else
      logger.info("FAILED")
    end
    render nothing: true
  end

the logger:

[object Object]

/data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/database_statements.rb:371:in block in commit_transaction_records' /data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/database_statements.rb:370:in each' /data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/database_statements.rb:370:in commit_transaction_records' /data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/database_statements.rb:218:in transaction' /data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/transactions.rb:208:in transaction' /data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/transactions.rb:311:in with_transaction_returning_status' /data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/transactions.rb:259:in block in save' /data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/transactions.rb:270:in rollback_active_record_state!' /data/viop/releases/167/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/transactions.rb:258:in save' /data/viop/releases/167/app/controllers/orders_controller.rb:216:in order_sold

Stack level too deep error when running test

I tried to run rspec and got this error:

/Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:125:in block (2 levels) in <class:Numeric>': stack level too deep (SystemStackError) from /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in ' from /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>' from /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in ' from /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>' from /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in ' from /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>' from /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:inblock (2 levels) in ' from /Users/Johnson/.rvm/gems/ruby-2.4.0/gems/activesupport-4.2.2/lib/active_support/core_ext/numeric/conversions.rb:131:in block (2 levels) in <class:Numeric>' ... 5588 levels... from /Users/Johnson/.rvm/gems/ruby-2.4.0/bin/rspec:22:inload' from /Users/Johnson/.rvm/gems/ruby-2.4.0/bin/rspec:22:in <main>' from /Users/Johnson/.rvm/gems/ruby-2.4.0/bin/ruby_executable_hooks:15:ineval' from /Users/Johnson/.rvm/gems/ruby-2.4.0/bin/ruby_executable_hooks:15:in `'

Does anyone have idea what might cause this?

To maintain data in a form after doing a validation in rails

I am validating my form but sending the error message cleans the fields and I want the data to be kept so that I only complete the ones I need

I have this code in the controller:

def create
mensaje=""
@farm = Farm.new(params[:farm])
if @farm.nombre==""  || !valid_prescence?(@farm.nombre)
  mensaje="Favor de capturar los datos que se encuentran como requeridos"
else
  @buscar=Farm.where(nombre: params[:farm][:nombre], tipo: params[:farm][:cliente_id])
  if @buscar.any?
    mensaje="La finca "+params[:farm][:nombre]+" ya se encuentra registrada en el sistema, favor de verificar."
  end
end

respond_to do |format|
  if mensaje !=""
    format.html { redirect_to new_farm_path, notice: mensaje }
    format.json { render json: @farm.errors, status: :unprocessable_entity }
  else
    if@farm.save
    format.html { redirect_to @farm, notice: 'Finca creada correctamente.' }
    format.json { render json: @farm, status: :created, location: @farm }
  else
    format.html { render action: "new" }
    format.json { render json: @farm.errors, status: :unprocessable_entity }
  end
end end end

At the moment of falling in the exception returns me to the form but with empty fields What I want is to be able to keep the data after sending the message

How to convert a string in to an array in ruby without using split method

I want to convert the string into an array without using any split method.

"Country ,blue,of, origin"

I want a desired output like this.

[Country ,blue,of, origin]

grape - table read as a constant

I'm using rails 5 and grape for api, I'm trying to create grape endpoint for the table application.

module GIS::API::V2
  class Applications < ::Grape::API
      get '/' do
        authorize! :read, Application
        status 200
        present Application.list(filter_params, current_user), with: Entities::ApplicationList, only_show: params[:only], person_base: true, current_ability: current_ability, user: current_user, nps_details: params[:nps_details]
      end
  end
end

I'm getting uninitialized constant GIS::API::V2::Applications::Application. I tried changing the class name and file name still the same error occurs.

lundi 24 avril 2017

How to get statements in previous transaction in after_commit?

I am wondering if it's possible to get SQL statements that were executed in the transaction in the rails after_commit callback and how?

My 2 coffee files interfering with each other in Rails

I know this is a little awkward question but the problem here is that in my rails app, I write 2 coffee script files both require window.onscroll fn.

when I implement them one at a tym both works fine, but when I include both, the script stops working... I know its a novice q. but plz help

Thank you.

here is the first script

rightBarControl = ->
  windowHeight = $(window).height()
  scrollHeight = $(window).scrollTop()
  rightBarWidth = $('#index_top_confession_div').width()
  #20% of .main width
  rightBarHeight = $('#index_top_confession_div').outerHeight()
  rightBarOffset = $('#index_confessions').offset().left + $('#index_confessions').outerWidth()
  rightBarTop = 75
  #30 because .head is 30px high
  if windowHeight - 75 < rightBarHeight
    #Again including 30 because of .head
    rightBarTop = windowHeight - rightBarHeight
  if windowHeight + scrollHeight - 75 >= rightBarHeight
    $('#index_top_confession_div').css
      position: 'fixed'
      left: rightBarOffset
      top: rightBarTop
  else
    $('#index_top_confession_div').css
      position: 'static'
      left: rightBarOffset
      top: rightBarTop
  return

$('#search').addClass 'form-control'
$(window).scroll rightBarControl
#Run control on window scroll
$(window).resize rightBarControl

The second script file..

 $(document).ready ->
  if $('.pagination').length
    $(window).scroll ->
      console.log('hey');
      url = undefined
      url = $('.pagination .next_page').attr('href')
      if url and $(window).scrollTop() > $(document).height() - $(window).height() - 200
        $('.pagination').html '<img src = \'/uploads/loader/loader.gif\' alt=\'loading...\'/>'
        return $.getScript(url)
      return
    return $(window).scroll()
  return

//= require_tree returns an error

I am using rails 5 for my application when I tried to include some code in my .coffee file.. it turned out that none of my coffee script file is working, then I checked my application.js and saw that //=require_tree . was missing, I added it but then came up with this error

- TypeError: Object doesn't support this property or method

dimanche 23 avril 2017

How to ensure attribute is updated only once in Rails 3 Active Record?

Wondering what could be the best way to handle situations where I need to update particular column and once updated it should not allow user to update again.

I tried using changed? method which checks for record that has been changed and not yet saved. But this would not check a particular attribute in that row.

Any suggestions?

Thanks in advance.

Change my default localhost port in Rails 5

I am using rails 5 which works with a default puma server and listen to localhost:3000

I want it to listen to a new port like 192.168.0.0:3000

Can anyone help ? thank you

Rails : iterate preview and download links in rails

**Two text fields for download and preview links to iterate in buttons**

     <div class="field">
    <%= f.text_field :preview, class: "form-control", placeholder: "preview link" %>
  </div>
  <div class="field">
    <%= f.text_field :download, class: "form-control", placeholder: "download link" %>
  </div>

Buttons for download and preview links:

<button class="btn btn-default"><i class="fa fa-eye"></i><%= link_to "Preview", @preview %></button>
    <button class="btn btn-default"><i class="fa fa-download"></i><%= link_to "Download", @download %></button>

enter image description here

Buttons links are not working.

can please show me how to iterate links inside buttons.

samedi 22 avril 2017

Rails: Paperclip multiple images upload error: No handler found for []

Trying to implement multiple images upload using Paperclip gem. I can see two images files in the parameters but I am getting an error no handler found for [].

views/passengerride/_form.html.erb:

<%= form_for @passengerride, :html => { :multipart => true} do |f| %>
 <div class="form-group ">
  <div class="control-label col-sm-2 requiredFiel">
   <%= f.label :title %>
  </div>
  <div class="col-sm-8">
   <%= f.text_field :title, class: "select form-control", placeholder: "Eg: Bedroom" %>
  </div>
 </div>

 <div class="form-group ">
  <div class="control-label col-sm-2 requiredFiel">
   <%= f.label :image %>
  </div>
  <div class="col-sm-8">
   <%= f.file_field :image, class: "select form-control", placeholder: "Eg: Bedroom", multiple: true %>
  </div>
 </div>
<% end %>

passengerrides_controller.rb:

def passengerride_params
 params.require(:passengerride).permit(:title, { image: :preview })
end

passengerride.rb:

has_attached_file :image,
                url: "/system/:hash.:extension",
                hash_secret: "abc123"
validates_attachment :image,
                   styles: { original: ['500x500>', :jpg] },
                   content_type: { content_type: ["image/jpeg", "image/jpg", "image/gif", "image/png"] },
                   presence: true,
                   size: { in: 0..5000.kilobytes }

Stopping counter with rails-timeago

I am timing a task from the date with the gem rails-timeago. The count appears in the view and I use the following code for this:

<% = Timeago_tag task.data,: nojs => true,: limit => 10.days.ago%>

I want to develop a button that when clicking the time count stops.

Can anyone help?

Thank you!

Hello everyone, my blog app with paperclip gem throws error while pushing it on heroku

remote:  !
remote: /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/helpers/rake_runner.rb:102:in `load_rake_tasks!': Could not detect rake tasks (LanguagePack::Helpers::RakeRunner::CannotLoadRakefileError)
remote: ensure you can run `$ bundle exec rake -P` against your app
remote: and using the production group of your Gemfile.
remote: rake aborted!
remote: NameError: undefined local variable or method `config' for main:Object
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/config/application.rb:4:in `<top (required)>'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/Rakefile:4:in `require_relative'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/Rakefile:4:in `<top (required)>'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/rake_module.rb:28:in `load'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/rake_module.rb:28:in `load_rakefile'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:687:in `raw_load_rakefile'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:96:in `block in load_rakefile'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:95:in `load_rakefile'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:79:in `block in run'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:178:in `standard_exception_handling'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/lib/rake/application.rb:77:in `run'
remote: /tmp/build_f02d7ba344a2a7bda4b7c4095d6f39b3/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
remote: vendor/bundle/bin/rake:17:in `load'
remote: vendor/bundle/bin/rake:17:in `<main>'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/ruby.rb:757:in `rake'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails4.rb:77:in `block (2 levels) in run_assets_precompile_rake_task'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:132:in `log'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails4.rb:71:in `block in run_assets_precompile_rake_task'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:18:in `block (2 levels) in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:40:in `yield_with_block_depth'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:17:in `block in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/vendor/ruby/cedar-14/lib/ruby/2.3.0/benchmark.rb:308:in `realtime'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:16:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:49:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:45:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails4.rb:70:in `run_assets_precompile_rake_task'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/ruby.rb:109:in `block (2 levels) in compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/ruby.rb:778:in `allow_git'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/ruby.rb:103:in `block in compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:18:in `block (2 levels) in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:40:in `yield_with_block_depth'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:17:in `block in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/vendor/ruby/cedar-14/lib/ruby/2.3.0/benchmark.rb:308:in `realtime'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:16:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:49:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:45:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/ruby.rb:92:in `compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails2.rb:57:in `block in compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:18:in `block (2 levels) in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:40:in `yield_with_block_depth'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:17:in `block in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/vendor/ruby/cedar-14/lib/ruby/2.3.0/benchmark.rb:308:in `realtime'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:16:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:49:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:45:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails2.rb:55:in `compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails3.rb:42:in `block in compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:18:in `block (2 levels) in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:40:in `yield_with_block_depth'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:17:in `block in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/vendor/ruby/cedar-14/lib/ruby/2.3.0/benchmark.rb:308:in `realtime'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:16:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:49:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:45:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails3.rb:41:in `compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails4.rb:41:in `block in compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:18:in `block (2 levels) in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:40:in `yield_with_block_depth'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:17:in `block in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/vendor/ruby/cedar-14/lib/ruby/2.3.0/benchmark.rb:308:in `realtime'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:16:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:49:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:45:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/rails4.rb:40:in `compile'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/bin/support/ruby_compile:20:in `block (2 levels) in <main>'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/base.rb:132:in `log'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/bin/support/ruby_compile:19:in `block in <main>'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:35:in `block in trace'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:18:in `block (2 levels) in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:40:in `yield_with_block_depth'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:17:in `block in instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/vendor/ruby/cedar-14/lib/ruby/2.3.0/benchmark.rb:308:in `realtime'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:16:in `instrument'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/instrument.rb:35:in `trace'
remote:   from /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/bin/support/ruby_compile:15:in `<main>'
remote:  !     Push rejected, failed to compile Ruby app.
remote: 
remote:  !     Push failed
remote: Verifying deploy...
remote: 
remote: ! Push rejected to secure-woodland-31687.
remote: 
To http://ift.tt/2oz67vC

vendredi 21 avril 2017

mini-profiler is not working

in the console of browser it shows error:- "NetworkError: 500 Internal Server Error - http://localhost:3000/mini-profiler-resources/includes.js?v=12b4b45a3c42e6e15503d7a03810ff33"

Ruby on Rails: how to copy objects from one category to another

I'm trying to copy some latest recipients (subscribers) to a new category in my newsletter app. I ran following lines of code in Rails console but instead of copying recipients to new category it moved latest 10 recipients to new category. It looks like recipient.clone is not working. I'm using Ruby v2.0.0 and Rails v3.2.11.

recipients = Recipient.where(category_id: 54).order('created_at DESC').take(10)
recipients.each{ |recipient| 
  @recipient_clone = recipient.clone
  @recipient_clone.category_id=63
  @recipient_clone.save
}

How to add two formats for single cell using WriteExcel?

Hi I'm using writeexcel (1.0.5, 0.6.19) gem in my RoR application. Is there any possibilities to add two formats for a single cell.

My requirement is to add two different colors for a single text.

for ex.

  sky is blue

I need the term blue in blue colored font in the single cell.

Rails: Allow one session to be :pinned at a time

I'm working on pinning a session for a company to the top of a list.

A company should be able to pin a single spark session to the top of their list. Because a company can only have a single pinned session, if they try to pin a new session it should save the newly pinned session and unpin any other session automatically.

Model:

class SparkSession < ActiveRecord::Base
  def pinned!
    self.pinned = true
    self.save!
  end
end

Controller:

class SparkSessionsController < SubdomainsController
  def index
    @spark_sessions = @company.spark_sessions.where(is_archived: false).order_by_pinned_then_created
  end
  def pin
    load_spark_session
    @spark_session.pinned!
    flash[:notice] = 'Spark Session pinned'
    redirect_to action: :index
  rescue ActiveRecord::RecordInvalid
    flash.now[:error] = 'Failed to pin Spark Session'
    redirect_to action: :index
  end
end

View:

%td= link_to 'Pin', pin_spark_session_path(tbl), method: :post

What is the most efficient way to handle the repinning of sessions for the company? Moreover, is there a way in the view or method more distinctive a pinned post with a styling element?

Rails nested fields_for with has_many relationship

Rails: 3.2.18

I am attempting to build a nested form which accepts attributes for a has_many relationship. In this case the form is for a Listing which is accepting attributes for a Shipment which is also accepting attributes for and has many ShipmentPackages. Here's a look at the code:

# listing.rb
class Listing < ActiveRecord::Base
  has_one :shipment
  accepts_nested_attributes_for :shipment
end

# shipment.rb
class Shipment < ActiveRecord::Base
  has_many :shipment_packages
  accepts_nested_attributes_for :shipment_packages
end

# Here's the form itself:
= form_for(@listing) do |f|
  = f.fields_for :shipment do |shipment_form|
    - @listing.shipment.shipment_packages.each do |shipment_package|
      = shipment_form.fields_for 'shipment_packages_attributes[]', shipment_package do |shipment_package_form|
        = shipment_package_form.text_field(:length)
        ...

# listings_controller.rb
class ListingsController < ApplicationController
  def update
    @listing.update_attributes(params[:listing])
  end
end

When the form is submitted, the parameters are getting passed in the way I would expect them to be:

Parameters: {"listing"=>{"shipment_attributes"=>{"shipment_packages_attributes"=>{"3"=>{"length"=>"11"}, "4"=>{"length"=>"6"}}}

In this case, the ids of my two existing ShipmentPackages are 3 and 4; therefore this ^ is what I would expect to see. However, rather than updating the attributes of the existing ShipmentPackages (3 and 4), this ignores them and is creating brand new ShipmentPackage records. My Shipment now owns 4 ShipmentPackages (3, 4, 5, 6).

Posting to blog in production environment for website without user authentication

I am working on website that I want to update my blog part of website in production. This website doesn't need to have user authentication.
But it's need to update and publish blog regularly. Can it done by making a devise model that just with one user as admin to playing with CRUD for blogs?
Or it doesn't need any authentication system or admin playing?

jeudi 20 avril 2017

Rails: Only allow one session to be :pinned at a time

A company should be able to pin a single spark session to the top of their list. Because a company can only have a single pinned session, if they try to pin a new session it should save the newly pinned session and unpin any other session automatically.

Model:

class SparkSession < ActiveRecord::Base
  def pinned!
    self.pinned = true
    self.save!
  end
end

Controller:

class SparkSessionsController < SubdomainsController
  def index
    @spark_sessions = @company.spark_sessions.where(is_archived: false).order_by_pinned_then_created
  end
  def pin
    load_spark_session
    @spark_session.pinned!
    flash[:notice] = 'Spark Session pinned'
    redirect_to action: :index
  rescue ActiveRecord::RecordInvalid
    flash.now[:error] = 'Failed to pin Spark Session'
    redirect_to action: :index
  end
end

View:

%td= link_to 'Pin', pin_spark_session_path(tbl), method: :post

What is the most efficient way to handle the repinning of sessions for the company? Moreover, is there a way in the view or method more distinctive a pinned post with a styling element?

Rails: How can I know the type of the argument a method expects to?

I'm programming in Ruby on Rails. How can I know the type of the argument a method expects to?

for example, lets say I have a method:

def foo(bar)
    @bar = bar
    @baz = get_user(@bar.user)
end

How can I know which object should I send to bar?

p.s: I am trying to understand a code not written by me

How begin rescue works with timeout?

Example

begin
  Timeout::timeout(5) do
    #some code
  end
  #other codes
  #other codes
rescue Timeout::Error
  Rails.logger.debug {" Command took longer than expected"}
end

When the #some codetakes longer then 5 sec will it run #other codes? I was guessing it will not run the #other codes. It will directly jump to rescue block. Correct me if i m wrong.

How to use procedure in rails

I'm trying to use execute_procedure in rails but when I call my proc what it returns it is a hash, I wanted it to have the bench reference to be able to use activerecord to falicitar, how do I do it?

Routine.in (Date.today)

Self.in (date)

  Self.execute_procedure ("test '# {date}'") End

**Irb (main): 079: 0> a.first => {"Rustic Wooden Lamp44", "schedule_time" => 2017-04-20 18:00:47 UTC, "start_time" => 6404, "routine_id" => 4858, Nil, "end_time" => nil, "result" => nil, "user_id" => nil, "justification" => nil, "incident_links" => nil, "status" => 0, "finiSh_routine_user_id "=> nil} <

Format Months in Rails views

In the rails console I can put in:

3.months => 3 months
1.months => 1 month

I would like to have this output in my views as well, I tried:

<%= @plan_months.months %>

And It gives this output:

 31104000

plan_months => 12 it's a Fixum

How can I get this output: 12 months

thanks

Building a shopping cart with rails

New to rails. I have seen several tutorials online, but am unable to get a simple shopping cart functionality. Following is my code and the error i am getting.

class CartsController < ApplicationController

def add
    @current_cart = @cart
    @current_cart = @current_cart.products.new(product_params)
    @current_cart.save
    session[:current_cart_id] = @current_cart.id

    redirect_to :back
  end



def delete
  end

  def show
    #@cart = initialize_cart.cart
  end

  private

  def product_params
    params.permit(:id)
  end

end

Application Controller

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_filter :initialize_cart

  def initialize_cart
    if session[:cart]
      @cart = Cart.find(session[:cart])
    else
      @cart = Cart.create
      session[:cart] = @cart.id
    end
  end

end

Link to Add to Cart Button

<%= link_to "Add to Cart", :controller => "carts", :action => "add", :id => @product.id, :class => "btn bg-turquoise"%>

routes.rb

get 'carts/add/:id', to: 'carts#add'

get 'carts/delete'

get 'carts/show', to: 'carts#show', as: 'showcart'

Error:

ActiveModel::UnknownAttributeError in CartsController#add

unknown attribute 'cart_id' for Product.

Extracted source (around line #5):

3 def add
4   @current_cart = @cart
**5     @current_cart = @current_cart.products.new(product_params)**
6   @current_cart.save
7   session[:current_cart_id] = @current_cart.id

Any help or guidance is appreciated. Thanks!

error while gem install rails Permission denied @ dir_s_mkdir - /var/lib/gems

$ gem install rails Fetching: concurrent-ruby-1.0.5.gem (100%) ERROR: While executing gem ... (Errno::EACCES) Permission denied @ dir_s_mkdir - /var/lib/gems

mercredi 19 avril 2017

Check how long tasks are taking to run

I made a small system that registers user tasks. The user logs in and registers a title with a description and a date of type datetime in the database. In the system it can view your tasks, delete and edit.

I would like to add a type of timer that starts counting from the defined time and date of the task, ie a timer that shows how long that particular task is consuming.

I installed the gem rails timeago and in one of my views I gave the command:

<% = Timeago_tag Time.zone.now,: nojs => true,: limit => 10.days.ago%>

With this I was able to show a timer on the screen that counts the time the page was loaded, but I would like to show the time the task is consuming.

I'm putting my schema code and my controlls tasks.

Schema:

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

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "tarefas", force: :cascade do |t|
    t.string   "titulo"
    t.text     "descricao"
    t.datetime "data"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "user_id"
    t.index ["user_id"], name: "index_tarefas_on_user_id", using: :btree
  end

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "", null: false
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at",                          null: false
    t.datetime "updated_at",                          null: false
    t.index ["email"], name: "index_users_on_email", unique: true, using: :btree
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
  end

  add_foreign_key "tarefas", "users"
end

Tarefa controller:

class TarefasController < ApplicationController

    before_filter :authenticate_user!

    def index
        @tarefa = current_user.tarefas.all
    end

    def show
        @tarefa = Tarefa.find(params[:id])
    end

    def new
        @tarefa = Tarefa.new
    end

    def edit
        @tarefa = current_user.tarefas.find_by(id: params[:id])
    end

    def create
         @tarefa = current_user.tarefas.new(tarefa_params)
         if @tarefa.save
            redirect_to @tarefa
         else
            render 'new'
         end
    end

    def update
        @tarefa = current_user.tarefas.find_by(id: params[:id])
        if @tarefa.update(tarefa_params)
            redirect_to @tarefa
        else
            render 'edit'
        end
    end

    def destroy
        @tarefa = current_user.tarefas.find_by(id: params[:id])
        @tarefa.destroy

        redirect_to tarefas_path
    end


    private
      def tarefa_params
        params.require(:tarefa).permit(:titulo, :descricao, :data)
      end
end

How to call event in another model?

I am using the workflow gem.

class Article
  include Workflow
  workflow do
    state :new do
      event :submit, :transitions_to => :awaiting_review
    end
    state :awaiting_review do
      event :review, :transitions_to => :being_reviewed
    end
    state :being_reviewed do
      event :accept, :transitions_to => :accepted
      event :reject, :transitions_to => :rejected
    end
    state :accepted
    state :rejected
  end
end

In same Article class I can call the event by doing this:

article = Article.new
article.submit!

But what if i want to call this event in other model file?

mardi 18 avril 2017

Rails How make a conditional inside a method on the model

I'm trying to make that just the user can feedback on a feedback method in the feedback model. but in the logs shows

NoMethodError (undefined method `total_feedbacks' for nil:NilClass)

so show to make a conditional in the model?

 def feedback_product

   user = User.find_by_id(attributes['user_id'])
  if user
    product.total_feedbacks += 1

    product.average_rating = product.feedbacks.where('buyer_feedback_date IS NOT NULL').rated(Feedback::FROM_BUYERS).average(:buyer_rating)

    product.save

  end

 end

the feedback belongs to user

 belongs_to :user

and user has_many :feedbacks

Expected "G-WWU6wMDhCr3VZ3YnHglw" to be empty -> RoR Tutorial Chapter 9

currently working on chapter 9 (Listing 9.26) of Hartls RoR Tutorial I experiece the following error while testing:

Failure:
UsersLoginTest#test_login_without_remembering [c:/Sites/workspace/sample_app/test/integration/users_login_test.rb:53]:
Expected "G-WWU6wMDhCr3VZ3YnHglw" to be empty.

/users_login_test.rb

require 'test_helper'

class UsersLoginTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:michael)
  end



    test "login with invalid information" do
      get login_path
      assert_template 'sessions/new'
      post login_path, params: { session: { email: "", password: "" } }
      assert_template 'sessions/new'
      assert_not flash.empty?
      get root_path
      assert flash.empty?
    end

    test "login with valid information followed by logout" do
      get login_path
      post login_path, params: { session: { email:    @user.email,
                                            password: 'password' } }
      assert is_logged_in?
      assert_redirected_to @user
      follow_redirect!
      assert_template 'users/show'
      assert_select "a[href=?]", login_path, count: 0
      assert_select "a[href=?]", logout_path
      assert_select "a[href=?]", user_path(@user)
      delete logout_path
      assert_not is_logged_in?
      assert_redirected_to root_url
      # Simulate a user clicking logout in a second window.
      delete logout_path
      follow_redirect!
      assert_select "a[href=?]", login_path
      assert_select "a[href=?]", logout_path,      count: 0
      assert_select "a[href=?]", user_path(@user), count: 0
    end

    test "login with remembering" do
      log_in_as(@user, remember_me: '1')
      assert_not_empty cookies['remember_token']
    end

    test "login without remembering" do
      # Log in to set the cookie.
      log_in_as(@user, remember_me: '1')
      # Log in again and verify that the cookie is deleted.
      log_in_as(@user, remember_me: '0')
      assert_empty cookies['remember_token']
    end
  end

/test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  #returns true if a test user is logged in
  def is_logged_in?
    !session[:user_id].nil?
  end

  # Log in as a particular user.
  def log_in_as(user)
    session[:user_id] = user.id
  end
end

class ActionDispatch::IntegrationTest

  # Log in as a particular user.
  def log_in_as(user, password: 'password', remember_me: '1')
    post login_path, params: { session: { email: user.email,
                                          password: password,
                                          remember_me: remember_me } }
  end
end

/sessions_controller.rb

class SessionsController < ApplicationController

  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      log_in user
      params[:session] [:remember_me] == '1' ? remember(user) : forget(user)
      remember user
      redirect_to user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
    log_out if logged_in?
    redirect_to root_url
  end
end

I'm confused, let me know if you need any other files.

Thanks in advance!

EDIT /sessions_helper.rb

module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Remembers a user in a persistent session.
  def remember(user)
    user.remember
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end

  # Returns the user corresponding to the remember token cookie.
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end

  # Returns true if the user is logged in, false otherwise.
  def logged_in?
    !current_user.nil?
  end

  # Forgets a persistent session.
  def forget(user)
    user.forget
    cookies.delete(:user_id)
    cookies.delete(:remember_token)
  end

  # Logs out the current user.
  def log_out
    current_user && forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end
end

EDIT2 /user.rb

class User < ApplicationRecord
  attr_accessor :remember_token
  before_save { self.email = email.downcase }
  validates :name,  presence: true, length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, length: { maximum: 255 },
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  has_secure_password
  validates :password, presence: true, length: { minimum: 6 }

  # Returns the hash digest of the given string.
  def User.digest(string)
    cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
                                                  BCrypt::Engine.cost
    BCrypt::Password.create(string, cost: cost)
  end

  # Returns a random token.
  def User.new_token
    SecureRandom.urlsafe_base64
  end

  # Remembers a user in the database for use in persistent sessions.
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end

  # Returns true if the given token matches the digest.
  def authenticated?(remember_token)
    return false if remember_digest.nil?
    BCrypt::Password.new(remember_digest).is_password?(remember_token)
  end

  # Forgets a user.
  def forget
    update_attribute(:remember_digest, nil)
  end
end

Validate form in rails when the user only enters spaces

I need to validate some fields so that it does not accept pure white spaces, that is, if the user only put spaces that throw an error to him. This is inside a form of ruby ​​on rails. I already tried it with regular expressions but it did not work

Rails Application#call is very slow

I'm seeing this Application#call take anywhere from 500 to 1500ms on every call which is soaking up memory on my Heroku dynos and causing timeouts. Any idea how to figure out what's inside this Application#call? Stuck on ideas. I replaced our app name with AppName.

New Relic screenshot

How does count work in Ruby when a string is set as the parameter?

How does count work in this code:

name= "abcdef"
puts name.count("aeiou")
puts name.count("^aeiou")

Does it count for the occurrences of "a", "e", "i", "o" and "u"?

If yes, how can I count the occurrences of "aeiou" as a single string?

Does the negation include counting for 'spaces'? Why/why not?

I want to migrate Rails 3 app to Rails 4.2.x

I am following this tutorial to implement sortable rails application. I am a newbie. Please guide how I can write this tutorial's example in Rails 4.

Grape entity multiple class inside module not loading

Currently i'm using grape and grape entity, the current following structure works fine.

# app/api/proj/api/v2/entities/committee.rb
module PROJ::API::V2::Entities
  class Committee < Grape::Entity; end
end

# app/api/proj/api/v2/entities/committee_base.rb
module PROJ::API::V2::Entities
  class CommitteeBase; end
end

# app/api/proj/api/v2/entities/committee_with_subcommittee.rb
module PROJ::API::V2::Entities
  class CommitteeWithSubcommittee < CommitteeBase; end
end

# app/api/proj/api/v2/entities/committee_list.rb
module PROJ::API::V2::Entities
  class CommitteeList < CommitteeBase; end
end

But when i have the following structure i'm getting uninitialized constant error.

module PROJ::API::V2::Entities
  class CommitteeBase < Grape::Entity; 
    expose :id
  end
  class CommitteeOffice < CommitteeBase; 
    expose :name
  end
end


present @committees, with: PROJ::API::V2::Entities::CommitteeOffice

Error:

uninitialized constant PROJ::API::V2::Entities::CommitteeOffice

How can i load committee office?

Rails, nested has_many association, finding sum of field of last children of each

I have nested models like (using PostgresSQL)

class User
  has_many :details
end

class Page
  has_many :details
  belongs_to :user
end

class Detail
  belongs_to :page
  #It has a column named "count"
end

What I need is say User with id=1, it has many pages with ids= 1,2,3. these pages with ids(1,2,3) has many details. What I need is to get latest detail of each of these pages and get sum of field named "counts" from these latest details

What I 'm doing now is

page_ids = current_user.pages.pluck(:id)
last_followers = Detail.select("DISTINCT ON(page_id) *").where(page_id: page_ids).order("page_id, created_at DESC")
last_followers.each { |detail| last_sum += detail.counts }

But it doesn't look ok to find page_ids, than details and than looping through all of them.

Is there a direct way like single query, thanks

Unable to install ruby 2.4.0 on mac

Hi i'm unable to install ruby 2.4.0

rvm version >> 1.29.1

rubygems version >> 2.6.11

I'm trying to install ruby 2.4.0 using the below command :

rvm install ruby-2.4.0

I'm getting the following error :

    Searching for binary rubies, this might take some time.
No binary rubies available for: osx/10.11/x86_64/ruby-2.4.0.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx_brew.
Installing requirements for osx_brew.
Updating system...........
Error running 'requirements_osx_brew_update_system ruby-2.4.0',
showing last 15 lines of /Users/bbc-admin/.rvm/log/1492510247_ruby-2.4.0/update_system.log
    http://ift.tt/1nuoqLP
and make sure `brew update` works before continuing.'
++ rvm_pretty_print stderr
++ case "${rvm_pretty_print_flag:=auto}" in
++ case "${TERM:-dumb}" in
++ case "$1" in
++ [[ -t 2 ]]
++ return 1
++ printf %b 'Failed to update Homebrew, follow instructions here:
    http://ift.tt/1nuoqLP
and make sure `brew update` works before continuing.\n'
Failed to update Homebrew, follow instructions here:
    http://ift.tt/1nuoqLP
and make sure `brew update` works before continuing.
++ return 1
Requirements installation failed with status: 1.

Please help me.. thanks in advance.

How to handel the windows pop ups in Rspec

While Uploading the image using r Spec it show error to specific field. find_by_id("abc").click aatach_file('element locator','path')strong text

lundi 17 avril 2017

Add sum array to active record object where something equals something

I want to sum my amount column plus display my original activerecord object together where my @val emp_no = @sell_back emp_no. Question is how can I combine the following because my @sell_back returns 4 active record objects and my @val only returns two values because I have only two emp_no with two records each. Any help would be greatly appreciated

Here is what I tried so far

Controller

def main_view
  @sell_back = SellBack.all
  @sell_back_tot = SellBack.all.group('emp_no')
  @val = @sell_back_tot.sum('amount')
end 

Here is my view

  %tr.trace-table
  -@sell_back.each do |sellback|
    -@val.each do |v|
      %tr.trace-table
        %td.trace-table{:style => 'border: solid black;'}
          %span.u= sellback.emp_f.capitalize
          %span.u= sellback.emp_l.capitalize
        %td.trace-table{:style => 'border: solid black;'}= sellback.amount
        %td.trace-table{:style => 'border: solid black;'}= v[1]
        %td.trace-table{:style => 'border: solid black;'}
          %span.u= best_in_place sellback, :status, :as => :select, :collection => ['Approve', 'Disapprove', 'Pending']

This doesn't work because it adds more rows..

dimanche 16 avril 2017

get object using has many through with polymorphic association

I am using rails 5.

Here I am using has many through with polymorphic

Tables are

categories, category_items, albums

Models are

Category, CategoryItem, Album

app/model/album.rb

class Album < ApplicationRecord
  has_many :category_items, as: :category_itemable, dependent: :destroy
  has_many :categories, through: :category_items
end

app/model/category.rb

class Category < ApplicationRecord
  has_many :category_items, dependent: :destroy
end

app/model/category_item.rb

class CategoryItem < ApplicationRecord
  belongs_to :category_itemable, polymorphic: true, optional: true
  belongs_to :category, optional: true
end 

I am able to get categories of a specific album through association. but now I need to get albums of a specific category.

Please find the solution and make sure don't use method. association should be clean and simple

Many Thanks in Advance

validation on parent model on the filed of child model

I have a model for book and a model for feedback i need a validation to check the presence of comments which is a field in feedback model in the parent model(book).using mongodb and rails

Couldn't find Product with 'id'=search

I'm just starting with RoR and i got an issue.

Earlier, I asked hear and nobody could fix it. I would like to make a simple search form, where i would search for a product name(title).

Here is the issue: "Couldn't find Product with 'id'=search"

Picture with the error

Here is my controller:

class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]
  helper_method :get_cost

  # GET /products
  def index
    @products = Product.all
    @products = Product.search(params[:find])
  end

  # GET /products/1
  def show
  end

  # GET /products/new
  def new
     @product = Product.new
    # ingredients_ids = @product.ingredients
  end

  # GET /products/1/edit
  def edit
  end

  # POST /products
  def create
    @product = Product.new(product_params)

    if @product.save
      redirect_to @product, notice: 'Product was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /products/1
  def update
    if @product.update(product_params)
      redirect_to @product, notice: 'Product was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /products/1
  def destroy
    @product.destroy
    redirect_to products_url, notice: 'Product was successfully destroyed.'
  end

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

    # Only allow a trusted parameter "white list" through.
    def product_params
      params.require(:product).permit(:title, :description, :category,   :price, :quantity, {ingredient_ids: []})
    end
end

Here is my model:

class Product < ActiveRecord::Base
  has_and_belongs_to_many :ingredients
  has_and_belongs_to_many :orders

  enum category: ["Culinária Italiana", "Culinária Oriental", "Culinária Árabe", "Culinária Brasileira"]

  TITLE_MIN_LENGTH = 3
  DESCRIPTION_MIN_LENGTH = 2

  validates :title, presence: true, :length => {:minimum => TITLE_MIN_LENGTH}, uniqueness: true
  validates :description, presence: true, :length => {:minimum => DESCRIPTION_MIN_LENGTH}

  def self.search(search)
    if search
        where(["title LIKE ?", "%#{search}%"])
    else
        all
    end
  end


end

here is my view:

<%= form_tag(products_search_path, :method => :get) do%>
    <%= text_field_tag :find, nil, placeholder:"Insira o que está procurando"%>
    <%= submit_tag "Pesquisar", :name => nil %> 
<% end %>

And just to finish, here is my routes:

Rails.application.routes.draw do
  get 'sessions/new'

  get 'users/new'

  get 'orders/show'
  get 'orders/new'

  resources :ingredients

  resources :products do
    get 'search'
  end

  resources :orders

  root "home#index"
  get    '/login',   to: 'sessions#new'
  post   '/login',   to: 'sessions#create'
  delete '/logout',  to: 'sessions#destroy'
  get  '/signup',  to: 'users#new'
  post '/signup',  to: 'users#create'

  get 'home/about'
  get 'home/contact'

  get "home" => "home#index"

end

Thanks for the attention, Miguel.

What is the difference between regular Block and defult Block in Ruby?

I am new to Ruby and would like to know why we use Blocks in Ruby instead of using methods in a regular way? Also what is the difference between regular Block and Default Block in Ruby? If you know any good resource that explain Blocks and their usage, please let me know. Thanks

syntax error, unexpected keyword_ensure, expecting ')' syntax error, unexpected keyword_end, expecting ')'

i am getting these errors in my rails project when i add a new product

" show.html.erb:52: syntax error, unexpected keyword_ensure, expecting ')'

show.html.erb:54: syntax error, unexpected keyword_end, expecting ')' "

even when there a only 50 lines in my show.html.erb

MY SHOW.HTML.ERB

<body style="background-image:url('/images/Linux Wallpaper.jpg');">

<div class="panel panel-default panel-list" style="width:70%;margin:20px auto;background-color: rgba(255,255,255,0.1);">
    <div class="panel-heading" style="background-color:rgba(126, 232, 173, 0.78);">
        <h3 class="panel-title" style="font-family:lucida;display:bold;">
        <% if @product.user == current_user %>
          <p style="float: right;"><%= link_to 'Edit', edit_product_path(@product), :style=>"background-color:rgb(10, 245, 61);padding: 10px 10px 10px 10px;border-radius: 6px; border:1px solid rgba(255,255,255,0.9);"  %> </p>

          <p style="float: left;"><%= link_to 'Back', products_path, :style=>"background-color:rgb(10, 245, 61);padding: 10px 10px 10px 10px;border-radius: 6px; border:1px solid rgba(255,255,255,0.9);" %><p>
           <center>YOUR PRODUCT : <%=@product.title%></center> 
        </h3>
    </div>
    <div class="panel-body" style="background-color:rgba(255,255,255,0.1);">

    <div class="row">
        <div class="col-lg-9 col-md-4" style="padding-left:30px;">
            <%= image_tag(@product.img_url.url(:large),:style => "height:400px;width:800px;border-radius: 4px; border:1px solid rgba(255,255,255,0.9);" %>
        </div>
        <div class="col-lg-2 col-md-2">
              <strong style="color:yellow;font-size:2em;font-weight:bolder;">Name:</strong><br>
            <div style="color:lightgreen;font-size:2em;">
            <%= @product.title%>
                </div>
        </div>
             <div class="col-lg-3 col-md-3">
              <strong style="color:yellow;font-size:2em;font-weight:bolder;">File Type:</strong><br>
            <div style="color:lightgreen;font-size:2em;">
            <%= @product.filetype%>
                </div>
        </div>
<div style="float:right;padding-right:10%;">
<div class="col-lg-2 col-md-2">
  <strong style="color:yellow;font-size:2em;font-weight:bolder;">Price:</strong><br>
        <div style="color:lightgreen;font-size:2em;">
  $<%= @product.price %>
        </div>
        </div>
    </div>
    <div style="float:right;padding-right:10%;">
<div>
  <strong style="color:yellow;font-size:2em;font-weight:bolder;">Tags:</strong><br>
        <div style="color:lightgreen;font-size:2em;">
  $<%= @product.all_tags %>
        </div>
        </div>
    </div>
    </div>
</div>
</div>

so can anyone help with my problem plz

samedi 15 avril 2017

Filter/Search objects in RoR

I'm just starting with ruby on rails, i got an issue that i could not resolve. First of all, i got an list of Products and i would like to filter/show by its name, using a search field. But, I'm getting this error, and i could not find an answer.

Error message:

commits on github that present my code:

http://ift.tt/2oyMIfH

ActionController::InvalidAuthenticityToken in DonationsController#create_user_account

I am new in ruby on rails and I am trying to send the post request using ajax to the controller method but the it throw the exception

ActionController::InvalidAuthenticityToken in DonationsController#create_user_account

I have google it but no idea what to do to solve this.

It is the main controller

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

Here is the code of donations controller

def create_user_account
    @donation = Donation.find(params[:a])
    @pars = [@donation.a]
    print @pars
    render plain: "OK"
  end

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

def set_campaign
  @campaign = Campaign.find(params[:campaign_id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def donation_params
  params.require(:donation).permit(:amount, :user_id, :campaign_id)
end

grape each entity in a single file

I want to have multiple classes inside grape entity file, this is the folder structure app/api/proj/api/v2/entities/committees.rb

module PROJ::API::V2::Entities
class Committee < Grape::Entity
expose :id

expose :name, :full_name, :email, :tag, :parent_id

expose :country do |entity, option|
  entity.parent.name if entity.parent.present?
end

# include Urls

private
  def self.namespace_path
    "committees"
  end
end

  class CommitteeWithSubcommittees < CommitteeBase
        # include ProfilePhoto 
        expose :suboffices, with: 'PROJ::API::V2::Entities::CommitteeBase'
      end

and inside the grape api

present @committees, with: PROJ::API::V2::Entities::Committee

is working. but if i present with

present @committees, with: PROJ::API::V2::Entities::CommitteeList

it is not working. But it works when i move it to a new file named committee_list.rb inside entities.

No matching Route error in Ruby on Rails

I am new in Ruby on Rails. I have been trying for two days to define a route for a method in the controller but error shows saying "No route matches [GET]". Here is the code

donations Controller:

before_action :set_donation, only: [:show, :edit, :update, :destroy, :create_user_account]
  before_action :set_campaign, only: [:new, :create_user_account]
//this is the method that i want to call 
  def create_user_account
  end

Here is my route file

Rails.application.routes.draw do
  resources :donations, except: [:new, :create]
 get 'donations/create_user_account' => 'donations#create_user_account'
  resources :campaigns do
    resources :donations, only: [:new, :create, :create_user_account]
    get 'donations/create_user_account' => 'donations#create_user_account'
  end
  resources :organizations

  devise_for :users

  root to: "campaigns#latest"
end

The routes are showing my route name but when i hit the route "no matching" route error occurs.

route1: campaign_donations_create_user_account_path GET /campaigns/:campaign_id/donations/create_user_account(.:format) donations#create_user_account route2:

donations_create_user_account_path  GET /donations/create_user_account(.:format)    
donations#create_user_account

I want to call route 2 but no route is working

I call my route 2 like this

http://localhost:3000/donations/create_uer_account

This is the error

enter image description here

vendredi 14 avril 2017

Rails Paperclip paperclip-av-transcoder saving

thank you so much for any help. I've tried for a few days and I can't figure it out. I am trying to build a video upload form. To my surprise, I can not find much info on the topic.

I am using Paperclip with paperclip-av-transcoder. It seems to be letting me create a Video.new record but I can not get it to save @user.videos.build(video_params).

class VideosController < ApplicationController

  def new
    @user = User.find(current_user)
    @video = @user.build_video
  end

  def create
    @user = User.find(current_user)
    @video = @user.videos.build(video_params)
    if @video.save
       redirect_to admin_ad_pg_path, :flash => { :error => "It worked!" }
    else
       redirect_to admin_ad_pg_path, :flash => { :error => "Nope. Didn't work." }
    end
  end

  private
    def video_params
      params.require(:video).permit(:avatar)
    end
end


Video Model:

class Video < ApplicationRecord
    belongs_to :user
    has_attached_file :avatar, :styles => {
    :medium => { :geometry => "640x480", :format => 'flv' },
    :thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10 }
    }, :processors => [:transcoder]
    validates_attachment :avatar, content_type: { content_type: /\flv\/.*\Z/ }
end

User Model

class User < ApplicationRecord
has_many :videos
end



 Video Form:
<%= flash[:error] %>
      <%= form_for @video, url: user_videos_path(current_user), controller: "videos", method: 'post', :html => { multipart: true } do |f| %>
        <div class="form-group">
          <%= f.label :avatar %>
          <%= f.file_field :avatar, class: 'form-control' %>
        </div>
      <%= f.submit 'Submit',class: 'btn btn-default' %>
      <% end %>

Thanks, Matt

Rails f.select Save Id an Name at the same time

I have a form with selection options. I want to add the ID and the Company Name when the company name is selected from the options. Is it possible to add multiple attributes in the f.select line of code? This is how my code looks:

<div class="field">
 <%= f.label 'Client' %>
 <%= f.select :client_id, Client.all.collect { |c| [ c.companyName, c.id ] } %>

I want to also assign the companyName to my :companyName attribute, but the id is the only thing that is being saved right now.

Thanks.

How to sort in pagination

Current code is showing results in random order but I want to display USA list first in order to India, UK and China.

@obj = User.where(:area => ["USA","India","UK","China"]).paginate(:page => params[:page], :per_page => 1)

I am using Paginate gem.

gem 'will_paginate', '~> 3.1.0'
gem 'will_paginate-bootstrap'

jeudi 13 avril 2017

why cause undefined method `empty? on rails?

I'm trying to loop on a related model and i have no idea why in the log is showing this

undefined method `empty?

'

someone have a idea why?

ActionView::Template::Error (undefined method `empty?' for #<Proback:0x007ffc8899c8c0>)

the proback belongs to product

and the product has_many probacks

product probacks view

<table class="completed_feedback_table">

  <tbody>
    <% @probacks.each do |proback| %>

      <tr>


        <td>
                     <div class="feedback_stars_rating" data-read-only="true" data-score="<%= proback.buyer_rating %>"></div>
        <%= proback.buyer_comment %></td>

      <td>



     <%=   link_to(proback.user.first_name, user_path(proback.user_id))%>



      </td>

      <td>
             <%= proback.buyer_feedback_date.strftime("%d/%m/%Y") %></td>


      </td>
    <td>

    </td>

  </tr>
  <% end %>


</tbody>
<tfoot>
  <tr>
    <td colspan="4">
  <%= render :partial => 'shared/proback_pagination'%>


    </td>
  </tr>
</tfoot>
</table>

controller probacks action

def probacks

    @product = Product.find(params[:id])
    @probacks =  Proback.joins(:product).where('products.id = ?', @product.id).paginate(:per_page => 22, :page => params[:page])

  end

Ruby regexp - test string begins with a specific string

Here is a typical string i want to test:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigkJyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCAAKAB4DAREAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAABgUH/8QAIxAAAgEEAQQDAQAAAAAAAAAAAQIDAAQFERMhIjGBBhIyQf/EABYBAQEBAAAAAAAAAAAAAAAAAAQCA//EACARAAICAgEFAQAAAAAAAAAAAAABAhEEIQMSEyIxYdH/2gAMAwEAAhEDEQA/AM4s7JWhdpEil5YyIzz/AFMTAjqR/em+lWkQyjjLQRXHG/1JU62DsGncS0D5XsXY2aHG/IYXkZIxLZyJCza1ye/HSiZqeqE4LW0w1lbVLbJXADhllIlCkdy7359AH3UcEvGjTIjUrDEX6q4kSL+L/a06HoDP2XMuo5sC2hs3DAnXnujoOS31tfP0bjJdtP6G5GaTMXpdixMr7JO991HTqKoS1cnZ/9k=

I am using validates_format with to check that a string begins with the following characters:

data:image/jpeg;base64

For the moment my code is but it's not working:

validates_format_of :imagebase64,  :with => %r{ \A(data:image/jpeg;base64) }i, :message => "is a invalid data uri base64 file"

Also how can I add something to the regexp so that it rejects if the string has any white space inside the string ?

Spring REST oauth2 API + Ruby on rails 2.3.0

I am calling Spring rest oauth api from ROR with is giving response as follows

{
    "access_token": "22cb0d50-5bb9-463d-8c4a-8ddd680f553f",
    "token_type": "bearer",
    "refresh_token": "7ac7940a-d29d-4a4c-9a47-25a2167c8c49",
    "expires_in": 119
}

now I want to send this access_token as http header in every ROR api. So how can I achieve that.

mercredi 12 avril 2017

Rails Application#call is very slow

I'm seeing this Application#call take anywhere from 500 to 1500ms on every call which is soaking up memory on my Heroku dynos and causing timeouts. Any idea how to figure out what's inside this Application#call? Stuck on ideas. I replaced our app name with AppName.

New Relic screenshot

Manage multiple recipients with one transaction id

I am building an e-commerce website where I need to charge buyer for a purchase e.g. buyer purchased an item in 20$, then 18$ will be transferred to seller account and 2$ will be transferred to application owner as fee. I need to do this transfer in a single transaction.

  1. I can do it using adaptive payments with multiple recipients but when redirect buyer to paypal for payment then page shows invoice with payment distribution(between owner and seller) which I don't want to show. I attached screenshot for the same as wellenter image description here. So, I dropped this option.

  2. Another option is I can collect full payment e.g. 20$ to owner's account when buyer transfers payment and then transfer seller's share in another transaction. But in this case I need to manage two different transaction ids which will be hard to manage in case of Refund.

Please let me know how can I distribute payment between multiple recipients in a single transaction without letting buyer know about it(as mentioned in case 1) and how can I manage refund with case 2? Please do a prompt reply

Ajax calls with Rails 5 using remote_function

I am trying to upgrading a 2.3.2 rails application to rails 5, i know that no more remote_function in rails 3,4,5. how can i fix the bug using Ajax this is the code:

<p><label for="medium">Medium: </label><%= collection_select(:order_item, :medium_id, @media,  :id, :label, { :always_prompt => "Select a medium" }, { :onchange => "#{remote_function(:url => { :action => "medium_changed" }, :with => "'order_item_id=#{@order_item.id}&order_id=#{@order_item.order.id}&medium_id='+value") }", :id => "order_item_medium_id", :name => "order_item[medium_id]" ,:class=>"form-control"} )  %></p>

sort_link with Polymorphic Relationship + Ransack

I have one polymorphic relationship

class Offer < ApplicationRecord
  belongs_to :offerable, polymorphic: true
end

class Company < ApplicationRecord
  has_many :offers, as: :offerable, dependent: :destroy
end

class Location < ApplicationRecord
  has_many :offers, as: :offerable, dependent: :destroy
end

Now Offers are offerable with either Company or Location.

In the both tables (Company, Location), name field is there in the database.

= sort_link(query, :offerable_of_Company_type_name) do
   %span{ class: ["btn btn-outline-success btn-sm", ('active' if params[:name])] } Name

Above code is working but I want to search with Company name as well as Location name so I will try below

= sort_link(query, :offerable_of_Company_type_name_or_offerable_of_Location_type_name_cont, 'name') do
  %span{ class: ["btn btn-outline-success btn-sm", ('active' if params[:name])] } Name

But, above code is not working. So how can I sort with two fields for offerable. I want to sort with Company name as well as Location name.

I'm using ransack for searching.

How to make a recursive mkdir with Rails SFTP?

Is it possible to create multiple level directories like /2017/04/11/ on a FTP Server via sftp.mkdir! "/2017/04/11"?

It returns Net::SFTP::StatusException: Net::SFTP::StatusException because I have neither a /2017 directory nor a /04 subdirectory.

Just sftp.mkdir! "/2017" creates one level.

Uninitialized constant for grape

I am using grape in rails and i'm getting the following error.

Uninitialized constant TMO.

I have this folder structure in grape app/tmo/root.rb and inside the root.rb file i have this code and when i try to mount i get the following error occurs - Unintialized constant TMO.

module TMO
  class Root < ::Grape::API
  end
end

when i make it to tmo and mount in routes its working.Is it possible to use the GIS or i should use Gis and why

No such file or directory -- rake [PROJECT-FOLDER-NAME] init ... (LoadError)

I have rails 3.2.0 application and ruby is - 2.1.2. When I'm running below command

rake assets:precompile 

I'm getting error like

.rvm/rubies/ruby-2.1.2/bin/ruby: No such file or directory -- rake [PROJECT-FOLDER-NAME] init ... (LoadError)
rake aborted!

What's wrong with Precompile not getting so please Help me

mardi 11 avril 2017

Expected "G-WWU6wMDhCr3VZ3YnHglw" to be empty -> RoR Tutorial Chapter 9

currently working on chapter 9 (Listing 9.26) of Hartls RoR Tutorial I experiece the following error while testing:

Failure:
UsersLoginTest#test_login_without_remembering [c:/Sites/workspace/sample_app/test/integration/users_login_test.rb:53]:
Expected "G-WWU6wMDhCr3VZ3YnHglw" to be empty.

/users_login_test.rb

require 'test_helper'

class UsersLoginTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:michael)
  end



    test "login with invalid information" do
      get login_path
      assert_template 'sessions/new'
      post login_path, params: { session: { email: "", password: "" } }
      assert_template 'sessions/new'
      assert_not flash.empty?
      get root_path
      assert flash.empty?
    end

    test "login with valid information followed by logout" do
      get login_path
      post login_path, params: { session: { email:    @user.email,
                                            password: 'password' } }
      assert is_logged_in?
      assert_redirected_to @user
      follow_redirect!
      assert_template 'users/show'
      assert_select "a[href=?]", login_path, count: 0
      assert_select "a[href=?]", logout_path
      assert_select "a[href=?]", user_path(@user)
      delete logout_path
      assert_not is_logged_in?
      assert_redirected_to root_url
      # Simulate a user clicking logout in a second window.
      delete logout_path
      follow_redirect!
      assert_select "a[href=?]", login_path
      assert_select "a[href=?]", logout_path,      count: 0
      assert_select "a[href=?]", user_path(@user), count: 0
    end

    test "login with remembering" do
      log_in_as(@user, remember_me: '1')
      assert_not_empty cookies['remember_token']
    end

    test "login without remembering" do
      # Log in to set the cookie.
      log_in_as(@user, remember_me: '1')
      # Log in again and verify that the cookie is deleted.
      log_in_as(@user, remember_me: '0')
      assert_empty cookies['remember_token']
    end
  end

/test_helper.rb

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  #returns true if a test user is logged in
  def is_logged_in?
    !session[:user_id].nil?
  end

  # Log in as a particular user.
  def log_in_as(user)
    session[:user_id] = user.id
  end
end

class ActionDispatch::IntegrationTest

  # Log in as a particular user.
  def log_in_as(user, password: 'password', remember_me: '1')
    post login_path, params: { session: { email: user.email,
                                          password: password,
                                          remember_me: remember_me } }
  end
end

/sessions_controller.rb

class SessionsController < ApplicationController

  def new
  end

  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      log_in user
      params[:session] [:remember_me] == '1' ? remember(user) : forget(user)
      remember user
      redirect_to user
    else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new'
    end
  end

  def destroy
    log_out if logged_in?
    redirect_to root_url
  end
end

I'm confused, let me know if you need any other files.

Thanks in advance!