lundi 31 octobre 2016

rails paypal adaptive undefined method `[]' for false:FalseClass

Someone is having this issue?

i place the sdk configure on: buy action

and on the log shows:

line 58 is PayPal::SDK.configure

NoMethodError (undefined method []' for false:FalseClass): app/controllers/orders_controller.rb:58:inbuy'

def buy require 'paypal-sdk-adaptivepayments'

PayPal::SDK.configure(
  :mode      => "live",  # Set "live" for production
  :app_id    => "APP-xxxxx",
  :username  => "xxxx.yyyy.com",
  :password  => "xxxx",
  :signature => "xxxxx" )



  @api = PayPal::SDK::AdaptivePayments.new


  order = Order.find(params[:id])
  store_amount = (order.total_price * configatron.store_fee).round(2)
  seller_amount = (order.total_price - store_amount) + order.shipping_cost

  @pay = @api.build_pay({
    :actionType => "PAY",
    :cancelUrl => carts_url,
    :currencyCode => "US",
    :feesPayer => "SENDER",
    :ipnNotificationUrl => ipn_notification_order_url(order),

    :receiverList => {
      :receiver => [{
        :email =>  order.product.vitrine.policy.paypal,
        :amount => seller_amount,
        :primary => true},
        {:email => configatron.paypal.merchant,
         :amount => store_amount, 
         :primary => false}]},
         :returnUrl => carts_url })

         @response = @api.pay(@pay)

         # Access response
         if @response.success? && @response.payment_exec_status != "ERROR"
           @response.payKey
           redirect_to @api.payment_url(@response)  # Url to complete payment
         else
           @response.error[0].message
           redirect_to fail_order_path(order)

         end

end

Class methods accessible in Rails console but not in Rails Model

I installed the rinku gem http://ift.tt/SSWSGU

I can then:

rails c

and execute a command like: Rinku.auto_link('This is some text with link: http://hello.com', mode=:all, 'target="_blank"', skip_tags=nil) right in the console.

But the same command won't work in after_save in class Post < ActiveRecord::Base

uninitialized constant Post::Rinku

How do I access the class methods in Rinku in my Post after_save filter?

dimanche 30 octobre 2016

Local file copy is getting created in the Rails application code base

i'm using rails 3.2.22 and ruby 2.2.

i'm creating a text file and i want to send that for download using send_to. My code works as expected but every time i hit the action one local copy of the file is getting created in my application root folder. I dont want this and file should directly go to download folder. Am i doing anything wrong ??

  def save_trunk_logs
    data = ""
    file = "test.txt"
    trunk_logs = some data
    File.open(file, "w") do |aFile|
      aFile.write("Trunk Name : #{trunk_name}\n")
      aFile.write("*"*100)
      aFile.write("\n")
      aFile.write("Time Stamp"+"\t"+"Log Message\n")
      trunk_logs.each do |msg|
      text =format_log_messages msg
        data << "#{data}\n"
     end
  end
send_file file, :type => 'application/text; charset=UTF-8', :disposition => 'attachment'
end

Any help is appreciated.

Thanks in advance.

Rails throws 'load_missing_constant: expected path_to_x to define X', yet it does

My error:

/Users/-/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:512:in `load_missing_constant': 
Unable to autoload constant Types::QueryType, expected /Users/-/project/app/graph/types/query_type.rb to define it (LoadError)

app/graph/schema.rb:

module Graph
  Schema = GraphQL::Schema.define do
    query Types::QueryType
  end
end

app/graph/types/query_type.rb:

module Graph
  module Types
    QueryType = GraphQL::ObjectType.define do
      name 'Query'
    end
  end
end

config/application.rb:

config.autoload_paths << "#{Rails.root}/app/graph"
config.autoload_paths << "#{Rails.root}/app/graph/interfaces"
config.autoload_paths << "#{Rails.root}/app/graph/types"
config.autoload_paths << "#{Rails.root}/app/graph/unions"

Rails correctly expects Types::QueryType to be defined in app/graph/types/query_type.rb, however - weirdly enough - somehow concludes that file does not define Types::QueryType, which it clearly does.

Even weirder: when jumping into a console, it only throws this error the first time Types::QueryType is requested. The second time however Types::QueryType resolves to the correct definition.

I'm probably doing something wrong here, but I just can't seem to find it.

samedi 29 octobre 2016

NameError in ProjectsController#index

In my rails app I am getting the following error:

NameError in ProjectsController#index
app/controllers/projects_controller.rb:6:in `index'

My routes look like this:

RailsStarter::Application.routes.draw do
resources :projects

root :to => 'pages#home'
match '/' => 'pages#home'
match '/overview' => 'pages#overview'
match '/recruitmentInfo' => 'pages#recruitmentInfo'

And the problem controller:

 class ProjectsController < ApplicationController

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

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

My investigations so far showed that Project is not yet initialized, but this shouldn't matter as it is a constructor, in its own class. I even tryed precompiling that by adding this line config.autoload_paths += %W( #{config.root}/app/controllers) to application.rb. Nothing seems yet to work. Any ideas will be greatly appreciated. Thanks!

Expected exactly 2 elements matching "a [href="/"]", found 0

I'm trying to check how many links are routed to root_path. My question is why the route in my _header.html.erb file are not counted by assert_select?

(I'm a beginner to code and rails and I'm following Michael Hartl's tutorial)

root_path is used in the page twice:

 <%= link_to "sample app", root_path, id: "logo" %>
 <li><%= link_to "Home",    root_path %></li>

Here is my code for the integration test:

require 'test_helper'
class SiteLayoutTest < ActionDispatch::IntegrationTest
  test "layout links" do
    get root_path
    assert_template 'static_pages/home'
    assert_select "a [href=?]", root_path, count: 2
    assert_select "a [href=?]", help_path
    assert_select "a [href=?]", about_path
    assert_select "a [href=?]", contact_path
  end
end

This is the partial code for my HTML file (_header.html.erb):

<header class="navbar navbar-fixed-top navbar-inverse">
  <div class="container">
    <%= link_to "sample app", root_path, id: "logo" %>
    <nav>
      <ul class="nav navbar-nav navbar-right">
        <li><%= link_to "Home",    root_path %></li>
        <li><%= link_to "Help",    help_path %></li>
        <li><%= link_to "Log in", '#' %></li>
      </ul>
    </nav>
  </div>
</header>

When I run $bundle exec rake test:integration, it gives me 1 failure which is:

FAIL["test_layout_links", SiteLayoutTest, 2016-10-20 16:03:19 +0000]
 test_layout_links#SiteLayoutTest (1476979399.42s)
        Expected exactly 2 elements matching "a [href="/"]", found 0..
        Expected: 2
          Actual: 0
        test/integration/site_layout_test.rb:8:in `block in <class:SiteLayoutTest>'

vendredi 28 octobre 2016

Extract all words with @ symbol from a string

I need to extract all @usernames from a string(for twitter) using rails/ruby:

String Examples:
"@tom @john how are you?"
"how are you @john?"
"@tom hi"

The function should extract all usernames from a string, plus without special characters disallowed for usernames... as you see "?" in an example...

How to configure Fine Uploader to make Rails-compatible requests?

Using Fine Uploader with Rails 3.2, I don't know how to configure Fine Uploader to make upload requests that the Rails backend can authorise.

The Fine Uploader front-end element works fine and targets my resource (uploads), but because the uploads#create endpoint is guarded by authorisation (user must be logged in) the request has to contain valid session information to be let through. And it doesn't, so the upload of course fails.

How do I make Fine Uploader make requests that contain the necessary information for Rails to accept this as part of the user's session?

For what it's worth I initialise the uploader like this:

app/views/uploads/index.html.haml

[ ...template... ]

:javascript
    var uploader = new qq.FineUploader({
        debug:true,
        element: document.getElementById("uploader"),
        request: {
            endpoint: '/uploads',
        }
    })

It makes a POST /upload request which is routed to upload#create, but fails authorisation because of checks in the controller like this:

def session_exists?
    return true if !session[:user_id].blank?`

Any insights appreciated.

Rails Gem for Searching

I have a webapp where I want to provide an advanced search in which the user enters an arbitrary amount of queries joined by AND's and/or OR's, like this:

(entered into the search box on the webpage)

name = "john" OR (occupation = "gardener" AND hobby.main = "reading")

In a prior post, I successfully implemented a system in which I directly convert queries formatted as above into valid SQL statements, and feed them straight into SQL to query the database.

This worked, but now I worry about three things:

  1. This wreaks of SQL injection
  2. If the user's input is invalid SQL throws an error which isn't very pretty...had some trouble handling these exceptions (though this part is doable).
  3. The code just seems really hacky and I wonder if there's a better way.

Well, I've heard there is a better way, by using search gems.

However, I've been having trouble finding gems that match my needs. Many of the gems seem too complex for what I need, and nothing that I've found made it clear exactly how you could implement specifically what I'm looking for -- where the user enters a dynamic number of queries joined by AND / OR statements.

Exactly how costly is it to just convert the statement straight to SQL syntax and inject it right in, like I'm doing right now? How easy is it to incorporate one of these gems for what I want? What would an "experienced" Rails developer do? I'm a complete noobie to Rails, so I don't have experience with any of this.

Radio buttons in rails not taking default value based on the data stored in the database

Am trying to create a profile page where the user can check "male" or "female". After saving the form, whenever the user visits the page again, the gender must be set by default based on the data stored in the database.

Am using the form_for helper here.

<%= form_for @profile do |f| %>
  <%= f.label :gender, "Male", :value => "m" do %>
    <%= f.radio_button :gender, "m" %>
  <% end %>
  <%= f.label :gender, "Female", :value => "f" do %>
    <%= f.radio_button :gender, "f" %>
  <% end %>
<% end %>

jeudi 27 octobre 2016

Assigning nested attributes to build_object

Is their a way to create this hash not to loop?

 {"0"=>{":comment_id"=>"52"}, "1"=>{":comment_id"=>"53"}, "2"=>{":comment_id"=>"15"}}

Output:

[{":comment_id"=>"52"}, {":comment_id"=>"53"}, {":comment_id"=>"15"}]

So it can perform:

@article = Article.new(article_params)
@article.build_comments([{":comment_id"=>"52"}, {":comment_id"=>"53"}, {":comment_id"=>"15"}])

@article.save

Xlsx file gives error on MS Excel once it is zipped using rubyzip and unzipped on windows

Actually my requirement is to zip some files in some folders. I have already many files saved on my server and associated with some objects. So I have to zip all the files related to one object somewhat like this:

  • Main Folder
    • Sub Folder
      • Another Folder
        • XLSX File

This is an example of my hierarchy. What I did is I created these folders copied the files in those folders and the create a zip using this code:

http://ift.tt/29BiZxu

found on the rubyzip library itself. But when I unzip this file on windows and open it in Microsoft Excel then I get the following error:

We found a problem with some content in 'FileName.xlsx'.Do you want us to try to recover as much as we can? If you trust the source of this workbook, Click Yes

Pressing Yes recovers the file but I don't have any idea why this error is coming. I have tried opening the excel file when it is copied on the server that is working fine, but once it is zipped and unzipped then the error comes. I have seen some various issues for this topic like:

xlsx compressed by rubyzip not readable by Excel

but got no help.

What I tried to do more is like stting the compression level and I tried setting it to Zlib::DEFAULT_COMPRESSION for rubyzip but in spite of that I had the same issue. Also at some places and even in the readme if rubyzip I found that we may use:

Use write_buffer instead open

And I tried it using on this line (the best I could find):

http://ift.tt/2eUwjgQ

But it threw me a different exception so if this is the solution I am not sure how to use it.

masonry-brick media-item blocks tooltips

The following is in a Rails 3 application:

<i class="fa fa-hourglass-half has-tooltip info-icon-small" aria-hidden="true" data-toggle="tooltip" data-placement="auto" data-original-title="This tooltip shows up as expected."></i>
<ul class="masonry media-grid" style="margin-top: 15px;">
    <li class="masonry-brick media-item">
        <h3>This text shows up</h3>
        <i class="fa fa-hourglass-half has-tooltip info-icon-small" aria-hidden="true" data-toggle="tooltip" data-placement="auto" data-original-title="No sign of this tooltip."></i>
    </li>
</ul>

When the page is viewed the first icon shows up with a working tooltip but the second icon's tooltip is never visible. Removing class="masonry-bick media-item" from each <li> element causes the tooltips to show up whilst, of course, making a mess of the layout.

Does anyone know why this happens, or any means of allowing the tooltips to display within the <li class="masonry-brick media-item"> elements?

mercredi 26 octobre 2016

Unknown 302 Redirect happening in Rails

I'm dealing with a 302 Redirect when trying to access certain network_hosts#show pages. It's not happening on all of them. I've been trying to diagnose the issue for the last 5 hours and an befuddled.

Here's how it goes....

User clicks the following link in view network_host/index.html.erb:

<%= link_to '<i class="fa fa-eye"></i>'.html_safe, network_host_path(h.id), "data-toggle" => "tooltip", "title" => "View" %>

The controller network_host#show kicks in:

class NetworkHostsController < ApplicationController
  before_action :get_company_and_locations

  def show
    @network_host = NetworkHost.find(params[:id])
    if @network_host
      @major_issues = get_host_issues(@network_host, @network_host.last_test, "major")
      @minor_issues = get_host_issues(@network_host, @network_host.last_test, "minor")
    end
  end
end

Which accesses helper methods in helpers/application_helper.rb:

def get_company_and_locations
  @company = current_user.company
  @devices =  Device.where(company_id: @company.id).order(name: :asc)
  @locations = if @company
    current_user.company_locations.order(:name)
  else
    []
  end
end


def get_host_issues(network_host, last_test, severity)
  get_company_and_locations
  # the issue_ids to remove since they are deferred
  deferred_ids = []
  @company.deferred_issues.each do |d|
    if d.network_host_id == network_host.id && d.expires_at.future?
      deferred_ids.push(d.issue_id)
    end
  end
  # figure out the issues
  results = last_test.results.select{|result| result.issue.severity == "#{severity}"}.collect{|issue| issue }
  issues = results.select{ |issue| issue.issue_id 
end

At this point, the network_hosts/show.html.erb view should show, but instead my log is showing a 302 Redirect:

I, [2016-10-26T18:47:52.347035 #31947]  INFO -- : Started GET "/network_hosts/4673" for 12.33.233.231 at 2016-10-26 18:47:52 -0500
I, [2016-10-26T18:47:52.349154 #31947]  INFO -- : Processing by NetworkHostsController#show as HTML
I, [2016-10-26T18:47:52.349218 #31947]  INFO -- :   Parameters: {"id"=>"4673"}
I, [2016-10-26T18:47:52.369483 #31947]  INFO -- :   Rendered layouts/_back_button.html.erb (0.4ms)
I, [2016-10-26T18:47:52.377738 #31947]  INFO -- :   Rendered network_hosts/show.html.erb within layouts/application (10.2ms)
I, [2016-10-26T18:47:52.378656 #31947]  INFO -- : Redirected to http://ift.tt/1j3J2cD
I, [2016-10-26T18:47:52.378816 #31947]  INFO -- : Completed 302 Found in 29ms (ActiveRecord: 9.7ms)

So, at this point, I don't see any reason there would be a redirect back to my root_url, do you?

The only thing I've been able to differentiate is that the network_hosts#show displays when there are no 'minor' issues (so 1 major/1 minor issues work, or 2 major/0 minor issues), but doesn't seem to work when there are 0 major and X minor issues. Which leads me back to get_host_issues function in application_helper#get_host_issues, but from here I'm stuck.

Here is the network_host/show.html.erb (trimmed down):

<div class="table-responsive">
  <table id="major_issue_table" class="table table-striped">
    <thead>
     <tr>
       <th>Severity </th>
       <th>Code </th>
       <th>Problem </th>
       <th><span class="nobr">Action</span></th>
     </tr>
    </thead>
    <tbody>
      <% @major_issues.to_enum.with_index(1).each do |result, index| %>
        <% issue = result.issue %>
          <tr>
             <td><%= issue_severity(issue) %></td>
             <td><%= issue.name %></td>
             <td><%= truncate(issue.problem, length: 100) %></td>
             <td>
                <a href='#' class='deferIssue' data-toggle='modal' data-tooltip='tooltip' data-resultid='<%= result.id %>' data-issueid='<%= issue.id %>' data-target='#deferIssueModal' title='Defer'><i class='fa fa-close'></i></a>
                <%= link_to '<i class="fa fa-eye"></i>'.html_safe, issue_path({id: issue.id, network_host: @network_host.id}), "data-toggle" => "tooltip", "title" => "View" %>
             </td>
          </tr>
      <% end %>
    </tbody>
  </table>
</div>

<div class="x_content">
   <div class="table-responsive">
     <table id="minor_issue_table" class="table table-striped">
        <thead>
            <tr>
               <th>Severity </th>
               <th>Code </th>
               <th>Problem </th>
               <th><span class="nobr">Action</span></th>
             </tr>
        </thead>
        <tbody>
           <% @minor_issues.to_enum.with_index(1).each do |result, index| %>
             <% issue = result %>
             <tr>
                <td><%= issue_severity(issue) %></td>
                <td><%= issue.name %></td>
                <td><%= truncate(issue.problem, length: 100) %></td>
                <td>
                  <a href='#' class='deferIssue' data-toggle='modal' data-tooltip='tooltip' data-resultid='<%= result.id %>' data-issueid='<%= issue.id %>' data-target='#deferHostModal' title='Defer'><i class='fa fa-close'></i></a>
                  <a href="#" data-toggle="tooltip" title="Defer"><i class="fa fa-close"></i></a>
                  <%= link_to '<i class="fa fa-eye"></i>'.html_safe, issue_path(issue.id), "data-toggle" => "tooltip", "title" => "View" %>
                 </td>
              </tr>
            <% end %>
         </tbody>
     </table>
   </div>
</div>

Show user.first_name devise Ruby on Rails?

I am quite new to Ruby on Rails. I am building a prototype of an application for a project of my but I have a error with devise.

I have created a migration so I users can fill in their first and last name. When a user is logged in I want to show "Hi, user.first_name". But I can't make it work.

This is the code I am using in the index.html.erb

I hope someone can help me with this issue,

Kind regards, Arend

PS this is the migration file:

add_column :users, :first_name, :string
add_column :users, :last_name, :string
add_column :users, :company_name, :string

Accessing first element of array in rails

I am getting below json from backend.

{ drug:
  {

    "id": "580f323ee4b06ffee69041a1",
    "direction": [
        {
            "direction": "test",
            "discarded": false
        }
    ]
  }
}

I dont want direction as array. I want it as object so I wrote method drug_format to parse json

My ruby on rails code for parsing is as follows :

def drug_format drug
{
  id: drug[:id],
  direction: drug[:direction][0],
}
end

Now when I am trying to run my code I am getting following error.

NoMethodError (undefined method `[]' for nil:NilClass):
    app/controllers/drugs_controller.rb:280:in `drug_format'
    app/controllers/drugs_controller.rb:15:in `block in index'
    app/controllers/drugs_controller.rb:14:in `each'
    app/controllers/drugs_controller.rb:14:in `index'

What can be the issue?

mardi 25 octobre 2016

how to get text_field value in a variable in rails

Hi I am new in ruby on rials, i want to get text_field value in a variable then this variable value send to MySql query and form_for using bootstrap model

I am sending the code please tell me where am i wrong..... thanks

this is edit button click on then call bootstrap model "#examplemodel1"

<div class="edit-recr-wrp1">  
   <button type="button" class="btn btn-primary fa fa-pencil-square-o" data-toggle="modal" data-target="#exampleModal1" data-whatever="<%= emp['offer_letter_id'] %>"></button> 
</div>

this is my "#examplemodel1" call from above button

<div class="modal fade" id="exampleModal1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  </div>
  <div class="modal-body">
    <div class="post-new-job head-border">
        <div class="form-body"> 
            <!-- edit employee information -->
            <div class="mydata1">
        <%= text_field :ol_id, { class: 'form-control', id: 'recipient-name' } %>
            </div>

            <%= form_for :employee_details, url: hr_path(:ol_id), method: :patch  do |f| %>             
                <div class="col-md-12">

                 <div class="mydata">
                   <%= f.hidden_field :offer_letter_id, { class: 'form-control', id: 'recipient-name' } %>
                 </div>

                 <div class="form-group">
                    <label class="control-label">Employee ID</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>
                      <%= f.text_field :employee_id, { :required => true, placeholder: 'E12345678', class: 'form-control' } %>
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="control-label">Bank Account</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-university"></i> </span>
                      <%= f.text_field :bank_ac, { :required => true, placeholder: '06464060852634865', class: 'form-control' } %>
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="control-label">Bank IFSC Code</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-code"></i> </span>
                      <%= f.text_field :bank_ifsc, { :required => true,  placeholder: 'SBI012356', class: 'form-control' } %>
                    </div>
                  </div>

                 <div class="form-group">
                    <label class="control-label">End of Date</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-calendar"></i> </span>
                      <%= f.text_field :work_end_date, {  placeholder: 'MM/DD/YYYY', id: 'datepicker1', class:"datepicker_style" } %>
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="control-label">Gender</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-male fa-female"></i> </span>
                      <%= f.select :gender, ['Male', 'Female'], { :required => true }, class: "form-control" %>
                    </div> 
                  </div>

                  <div class="form-group">
                    <label class="control-label">Spouse Name</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>
                      <%= f.text_field :spouse_name, { :required => true, placeholder: 'Father/Mother/Wife name', class: "form-control" } %>
                    </div>
                  </div> <br>

                  <div class="form-group">
                    <a><%= f.submit "Edit Employee Details", :class => "btn btn-primary" %></a> 
                  </div>
                </div>
                <div class="col-md-2"></div>                
            <%- end -%>
        </div>      
    </div>
   </div>
</div>

this is my jquery code

<script type="text/javascript">
    $('#exampleModal1').on('show.bs.modal', function (event) {
      var button = $(event.relatedTarget)
      var recipient = button.data('whatever')
      var modal = $(this)
      modal.find('.mydata1 input').val(recipient)
    });
</script>

In this model offer_letter_id display into text_field:old_id

<div class="mydata1">
    <%= text_field :ol_id, { class: 'form-control', id: 'recipient-name' } %>
</div>

But I can not take this value in a variable. I want to pass this value in url: hr_path(variable value)

<%= form_for :employee_details, url: hr_path(:ol_id), method: :patch  do |f| %> 

Create data in intermediate table + has_and_belongs_to_many association in Rails

I have these 2 objects

box_id => 2 product_id => 3

how to create a entry in boxes_products table

Thanks in advance.

Using CanCanCan in a view failing tests

so I'm working on a project that is using rails, CanCanCan and rspec. I have an ability

 can :set_to_user, Post

Then in my view I have

class: "btn btn-primary #{disable_button(!(can? :set_to_user, post))}

This works in a view, but it seems to fail during tests giving the error:

ActionView::Template::Error:
       Devise could not find the `Warden::Proxy` instance on your request environment.
       Make sure that your application is loading Devise and Warden as expected and that the `Warden::Manager` middleware is present in your middleware stack.
       If you are seeing this on one of your tests, ensure that your tests are either executing the Rails middleware stack or that your tests are using the `Devise::Test::ControllerHelpers` module to inject the `request.env['warden']` object for you.

I'm not sure what is causing it, but any help would be greatly appreciated?

Rails Form: How to handle multiple selections in drop-down menu

I've been playing around with my form where I have a drop-down menu where you can select multiple options:

f.select :hobbies, [
                    ['First First First First','1'],
                    ['Second Second Second Second','2'],
                    ['Third Third Third Third','3'],
                    ['Fourth Fourth Fourth Fourth','4'],
                    ['Fifth Fifth Fifth Fifth','5'],
                    ['Sixth Sixth Sixth Sixth','6'],
                   ],
                   {},
                   {:multiple => true}

But I'm so confused at what the heck this thing is putting into my hobbies attribute (which is a string).

When I print out the contents after selecting the first three options:

<%= @user.hobbies %>

I get this junk:

--- - '' - '1' - '2' - '3'

So clearly it's getting the '1', '2', and '3' that I selected, which is good. But the rest of the output is weird looking.

All that I want to do is be able to print '1', '2', and '3' (or whatever options were selected). Of course, I could parse these values out of the giant string based on it's dash-separated format, but that seems the wrong way to do it.

I saw something about turning "hobbies" into an array by making it "hobbies[]", but that gives the odd error:

(wrong number of arguments (0 for 1..2))

So how exactly am I supposed to handle this stuff internally?

How does Rails View Helper work

I recently came across a tricky situation related to rails view helpers. The situation is like follows-

I am having a controller as Feature1::Feature1.1::Feature1.1.1Controller. The Feature1.1 also includes other controllers like Feature1.1.2Controller, Feature1.1.3Controller...

So ofcourse related view helpers in folder app/helpers/feature1/feature1.1/...

Now the real problem I am facing is that a few helpers for feature1.1 includes the same method name method1 with related definition.

I was wondering how rails identifies all these helpers as I am noticing that the method1 i.e. being called in a view for the controller feature1.1.1 is using the definition of the method1 i.e. written for the controller feature1.1.2.

So does rails consider all helper modules defined in one folder as one?

In a view feature1/feature1.1/feature1.1.1/index I am making a method call for method1.

I am using rails3

lundi 24 octobre 2016

Cannot modify association ":has_many." using Ruby on rails

I'm working with three tables as follows:

article.rb

class Article < ActiveRecord::Base
  has_many :comments
  has_many :comentarios, :through => :comments
end

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :article
  has_many :comentarios 
end

and comentario.rb

class Comentario < ActiveRecord::Base
  belongs_to :article
end

Everything works fine until I attempt to add a 'comentario' and returns this error

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection in ComentariosController#create 
Cannot modify association 'Article#comentarios' because the source reflection class 'Comentario' is associated to 'Comment' via :has_many.

This is the code I use to create a new 'comentario'

comentarios_controller.rb

class ComentariosController < ApplicationController

  def new
      @comentario = Comentario.new
  end

  def create
   @article = Article.find(params[:article_id])
   @comentario = @article.comentarios.create(comentario_params)
   redirect_to article_path(@article)
 end

 private
   def comentario_params
     params.require(:comentario).permit(:comentador, :comentario)
   end
end

The output returns an error in the line where I create @comentario from calling @article but I can't see why since Ruby documentation says that once I associate comentario to article using :through, I can simply call something like @article.comentario.

Any idea of what is causing this error? or do you have any suggestion on how to achieve this association in any other way?

Can I call a method inside another method

I am trying to add a tractor_beam instance method that takes a string description of an item as a parameter (e.g., "cow"). When called, the method should disable the shield, add the item to the inventory along with the ship's current location. I keep getting an error message when I run the tractor beam, is it possible to run the disable_shield inside the tractor_beam?

Here is the class I created:

class Spaceship
attr_accessor :name, :location, :item, :inventory
attr_reader :max_speed
  def initialize (name, max_speed, location, item)
    puts "Initializing new Spaceship"
    @name = name
    @max_speed = max_speed
    @location = location
    @item = item
    @inventory = {}
   end

  def disable_shield
    puts "Shield is off!"
   end

  def enable_shield
    puts "Shield is on!"
   end

  def warp_to(location)
     puts "Traveling at #{max_speed} to #{location}!"
     @location = location
   end

  def tractor_beam(item)
    disable_shield
    @inventory[@location] = item
   end

 end

Ruby ERB template separate files

I have the following two files: shoplist.html.erb, shoplist.rb.

I want these two files to create an html file called list.html Here is the code to the first and second file.

shoplist.html.erb

      <!DOCTYPE html>
<html>
<head>
<% # %A - weekday, %d - day of the month, %B - full month name, %Y - year %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Shopping List for <%= @date.strftime('%A, %d %B %Y') %></title>
</head>
<body>
  <h1>Shopping List for <%= @date.strftime('%A, %d %B %Y') %></h1>
            <p>You need to buy:</p>
            <ul>
              <% for @item in @items %>
                <li><%= h(@item) %></li>
              <% end %>
            </ul>
  </body>
  </html>

shoplist.rb

require 'erb'

def get_items()
  ['bread', 'milk', 'eggs', 'spam']
end
def get_template(file)
  str = ""
  File.open(file,"r") do |f|
    f.each_line do |line|
      str << line
    end
  end                                                                                                                                 
  str
end

class ShoppingList
  include ERB::Util
  attr_accessor :items, :template, :date

  def initialize(items, template, date=Time.now)
    @date = date
    @items = items
    @template = template
  end

  def render()
    ERB.new(@template).result(binding)
  end

  def save(file)
    File.open(file, "w+") do |f|
      f.write(render)
    end
  end

end
list = ShoppingList.new(get_items, get_template(ARGV[0]))
list.save(File.join(ENV['PWD'], 'list.html'))

I know these files should theoretically work, but I don't know the proper way to run them through the terminal. These files were found online at the following link: link

When I look at the code, I notice that it takes in an argument for the filename. My theory was to pass the shoplist.html.erb file in as the argument through the terminal to get it to properly create the file. This was the terminal command I tried:

ruby shoplist.rb shoplist.html.erb

When I did that however it gave me the following error:

shoplist.rb:38:in `<main>': undefined local variable or method `list' for main:Object (NameError)

Can someone tell me what I'm doing wrong? Both of those files are in the same directory. I thought I could simply pass in the filename and have the get_template() function read the contents to create the html file. This doesn't appear to be the case. Thanks!

remember previous input value in ruby

I have this sample class below.

class MyClass
  def initialize(options = {})
    @input = options[:input]
  end

  def trigger
    # I want to remember previous input value if this method called.
    input
  end
end

How can I store or remember the previous value that was previously input? For example.

my_class = MyClass.new(input: "first")
my_class.trigger
=> first

If I call:

my_class.input = "second"

I want to remember the previous value input which is "fisrt". How can I achieve this?

Assets not rendering in production rails

I have precompiled the assets in production but the application is not able to load the assets. My app is deployed on AWS EC2

enter image description here

I checked in the server in public/assets folder the application.css is present but still it says 404 error.

My production.rb configuration is

enter image description here

Ruby on Rails - JSON parse error unexpected token

I read json file after load it into json but i got error JSON::ParserError unexpected token at, i couldn't json parse.Below i mentioned what i got output after file read

Here my code,

file = File.read("sample.json") 
hash = JSON.load(file)

after read my json file,

"{\"rename\"=>[{\"from\"=>\"TTTC\", \"to\"=>\"AAAB\"}, {\"from\"=>\"AAAA\", \"to\"=>\"Description\"}, {\"from\"=>\"AAAC\", \"to\"=>\"test\"}], \"drop\"=>{\"fields\"=>[\"AAAG\", \"AAAH\"]}}"

Retreive Values from Relationship table of has_and_belongs_to_many on Rails5

I have two tables Role and User, and I linked those two tables with has_and_belongs_to_many relationship with rails.

I'm successfully insert the data into the third table which is created by has_and_belongs_to_many relationship. Using the following code

def create
user_params[:password] = User.hash(user_params[:password])
@user = User.new(:first_name => user_params[:first_name],
                 :last_name=>user_params[:last_name],
                 :email => user_params[:email],
                 :contact_number=>user_params[:contact_number],
                 :password=>user_params[:password])

@roles = user_params[:roles];
for role in @roles
  @user.roles << Role.find(role)
end
if @user.save
  respond_to do |format|
    msg = { :status => "ok", :message => "User Creation Success!" }
    format.json  { render :json => msg }
  end
end
end

Now my problem is how do I read the valuse from the relationship table and how do I update any value to the relationship table.

undefined method `gsub' for nil:NilClass or how to use gsub method in rails

I want to generate an Employee_ID with serially, I have fixed a initial employee id in database table. the format is "E36162000", I am taking last employee id from table then extract only integer value then add one, this will be next employee id.

But in this gsub() method is not working, gsub method extract integer is perfectly, link Next Employee_id = E36162001

But when am i submit then error comes. I am sending code and screen sort please help me

_employee_details.html.erb this is my view

<div class="modal-body">
    <h2 class="text-center">Add <span>Employee Details</span></h2>
    <div class="post-new-job head-border">
      <div class="alert alert-success" role="alert" id='success-job' style='display:none;'>Employee Details is successfully added.</div>
        <div class="form-body">             
            <%= form_for(:employee_details, :url => {:controller => 'hr', :action => 'create'}) do |f| %>                   
                <div class="col-md-12">
                <!--auto generate emp id-->
                <% @last_emp_id = EmployeeDetail.select("employee_id").last %>
                <% emp_id = @last_emp_id.employee_id  %>
                <% emp_id_sub = emp_id.gsub(/[^\d]/, '') %>
                <% auto_generate_id = 'E'.to_s + (emp_id_sub.to_i + 1).to_s %>
                <h1> Employee ID : <%= auto_generate_id %> </h1>


                <div class="mydata">
                 <%= f.hidden_field :offer_letter_id, { class: 'form-control', id: 'recipient-name' } %>
                </div>

                 <div class="form-group">
                    <label class="control-label">Employee ID</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>
                      <%= f.text_field :employee_id, { :value => auto_generate_id, :disabled=>true , :required => true, placeholder: 'E12345678', class: 'form-control' } %>
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="control-label">Bank Account</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-university"></i> </span>
                      <%= f.text_field :bank_ac, {placeholder: '06464060852634865', class: 'form-control' } %>
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="control-label">Bank IFSC Code</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-code"></i> </span>
                      <%= f.text_field :bank_ifsc, {placeholder: 'SBI012356', class: 'form-control' } %>
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="control-label">End of Date</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-calendar"></i> </span>
                      <%= f.text_field :work_end_date, {  placeholder: 'MM/DD/YYYY', id: 'datepicker', class:"datepicker_style" } %>
                    </div>
                  </div>

                  <div class="form-group">
                    <label class="control-label">Gender</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-male fa-female"></i> </span>
                      <%= f.select :gender, ['Male', 'Female'], { }, class: "form-control" %>
                    </div> 
                  </div>

                  <div class="form-group">
                    <label class="control-label">Spouse Name</label>
                    <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>
                      <%= f.text_field :spouse_name, { placeholder: 'Father/Mother/Wife name', class: "form-control" } %>
                    </div>
                  </div> <br>

                  <div class="form-group">
                    <a><%= f.submit "Add Employee Details", :class => "btn btn-primary" %></a> 
                  </div>
                </div>
                <div class="col-md-2"></div>                
            <%- end -%>
        </div>      
    </div>
   </div>

employee_details.rb this is my model

class EmployeeDetail < ActiveRecord::Base
   belongs_to :user
   validates :offer_letter_id, presence: true 

end

hr_controller.rb this is my controler

class HrController < ApplicationController
def new
    @employees = EmployeeDetail.new
end

# edit employee information
def edit
    @employees = EmployeeDetail.find(params[:id])
end

def create
    @employees = EmployeeDetail.new(employee_params)
    if @employees.save
        redirect_to :action => 'internal_employee_page'
    else
        redirect_to :action => 'internal_employee_page'
    end
end

def show
    @employees = EmployeeDetail.find(params[:id])
end

def update
    @employees = EmployeeDetail.find(params[:id])

    if @employees.update(employee_params)
        redirect_to :action => 'internal_employee_page'
    else
        redirect_to :action => 'internal_employee_page'
    end
end

private

    def employee_params
         params.require(:employee_details).permit(:offer_letter_id, :employee_id, :bank_ac, :bank_ifsc, :spouse_name, :gender, :work_end_date)
    end     

end

my layout View enter image description here

**Error in this line **

<% emp_id_sub = emp_id.gsub(/[^\d]/, '') %>

error is enter image description here

When am i Click on submit button then error is generate but data is save in employee_details table except Employee_Id

Learning Ruby ERB Templates

I'm trying to learn Ruby ERB Templates using the following guide: Tutorial Link

I am on the "very simple example" section with the following code:

require 'erb'

weekday = Time.now.strftime('%A')
simple_template = "Today is <%= weekday %>."

renderer = ERB.new(simple_template)
puts output = renderer.result()

I wanted to run this code to generate an html file so I created a file called

testing.html.erb

and ran the code with the following command:

erb testing.html.erb > new-file.html

When I did that through the terminal several errors popped up and the html file that was generated was blank. Here are the errors that I received: enter image description here

I was hoping someone could tell me what i was doing wrong. Am I forgetting something? Or am I not running the erb command correctly? Any help would be greatly appreciated. Thanks!

How to treat "\n" as new line in ruby variable

I have a string

       x = "hello\nHi"

When i do puts x, its working fine i.e the output becomes

    hello
    hi

but my objective is to when i type the variable name i.e

    input = x
    output should be
    hello
    hi

Is there any way to achieve this?

Reason: I am doing a API call, the response is xml but in the xml it has "\n" before each entry. Resonse from API is

     <?xml version='1.0' encoding='iso-8859-1'?>\n<!DOCTYPE data [\n  <!ELEMENT data (record+)>\n  <!ELEMENT record (first_element,last_element)>\n   <!ELEMENT first_element (#PCDATA)>\n   <!ELEMENT last_element (#PCDATA)>\n]>\n<data>\n    <record>\n <first_element>hello</first_element>\n <last_element>hi</last_element>\n
    </record>\n</data>       

But I want in the following format

<?xml version='1.0' encoding='iso-8859-1'?>
<!DOCTYPE data [
  <!ELEMENT data (record+)>
  <!ELEMENT record (first_element,last_element)>
   <!ELEMENT first_element (#PCDATA)>
   <!ELEMENT last_element (#PCDATA)>
]>
<data>
    <record>
        <first_element>hello</first_element>
        <last_element>hi</last_element>
    </record>
..
..
</data>

So that I can parse it using some gems such as nokogiri or something else.

Any lead in this regard would be of great help

samedi 22 octobre 2016

How to update Ruby 2.2.4 to 2.2..5

The reason I need to update to 2.2.5 is because whenever I run bundle install I'm receiving an error:

ERROR: Error installing ruby_dep:

ruby_dep requires Ruby version >= 2.2.5, ~> 2.2.

So I guess in order to avoid this I need to update to 2.2.5 I went to http://ift.tt/1qPi5SY and I downloaded the first link. I ended up with a ZIP file that I have no clue what to do with. I tried another method with: $ ruby update --system but got in return

c:\RailsInstaller\Ruby2.2.0\bin\ruby.exe: No such file or directory -- update (LoadError)

What should I do? Note: I'm using windows

How to send mails automatically using whenever gem

I used when ever gem to send mails every day but it's not sending.I am using amazon linux ec2 instance.please look at my code once.

schedule.rb:

every 5.minutes do runner "Listings.today_expired_spaces" end

Listings.rb:(model-file)

def today_expired_spaces @list=List.find_by_date(Date.today) UserMailer.today_expired_list(@list).deliver
end

In production: after running these commands I am getting responses like this 1.whenever -w

[write] crontab file written

2.whenever -i [write] crontab file updated

3.whenever

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /bin/bash -l -c 'cd /home/ubuntu/my_server && bundle exec script/rails runner -e production '\''Spaces.today_expired_spaces'\'''

[message] Above is your schedule file converted to cron syntax; your crontab file was not updated.

[message] Run `whenever --help' for more options.

please provide solution to this.

Ruby on Rails 4: Where i have to put Common code?

I am new to Ruby on rails. i am using rails 4.1.6 and what i want is to make log of all the process in one text file (like index page accessed, view page access etc..). for that i want to create common function, in which i can pass my text as agrs, i had do some R&D on that and i found this : In Rails, where to put useful functions for both controllers and models, but it seems that it is not working with active admin resources. so, for active admin controller and model, i have to create any other modules (i.e. on other location let say /admin/) or anything else i have to do ?

is there any global location that we can use in active admin like component in cakephp.

thanks

vendredi 21 octobre 2016

Recover or reset local login information managed by the Devise gem

I recently inherited a small Ruby on Rails platform that was more or less abandoned by its previous developer. It uses the Devise gem for user authentication/management/privileges. I have the administrative login for the live version of the platform online, but I don't know the administrative login if I just run the server locally via bin/rails server. I can't get into contact with the previous web developer.

My question is, how do I gain administrative privileges via the Devise gem when I don't have the administrative login for the local version of the application? Is there a way to reset the users managed by the Devise gem or add a new user with administrative privileges without knowing the login information of a current administrator? I need to be able to easily view pages that are only visible to users with elevated privileges without having to do a full deploy and then inspect the changes online.

rails 3.2.1 and mysql where condition with nil issue (it toggles in no record and proper result)

If I run the following query in rails console On first run it returns 7 rows and 2nd run it returns 0 rows, its keeps toggling...

@site.site_pages.published\
.where(:is_visible => true,:parent_id => nil,:lang_parent_id => nil)\
.order("position ASC")

=> [ARRAY OF RECORDS]
-- {Returns 7 rows}

@site.site_pages.published\
.where(:is_visible => true,:parent_id => nil,:lang_parent_id => nil)\
.order("position ASC")

=> []
-- {Returns 0 rows}

As a fix/work around I tried this, which worked fine, but need to know the root cause

@site.site_pages.published\
.where(:is_visible => true,:parent_id => [nil, ''],:lang_parent_id => [nil, ''])\
.order("position ASC")

NOTE: If i run the to_sql query in mysql, it works fine, so considering nothing to do with mysql version etc, but its 5.6.

Select options from multi-select dropdown

I am using select_tag from rails with bootstrap multi-select functionality. I am able to show options. But how to select options using jquery on page load.

select tag code <%= select_tag 'test', options_from_collection_for_select(@test, "id", "name"), :class => "form-control", :multiple => "multiple" %>

$('#test').multiselect({ 
  includeSelectAllOption: true,
  enableFiltering:true         
});  

When i use

 $("#test").val(["some_value_of_option", "some_value_of_option"]).prop("selected", true);

The above code is not working to select options. Thanks in advance for help..

jeudi 20 octobre 2016

Can't run middleman server. What's wrong?

I'm using Windows, I have Ruby21 (C:\Ruby21) and RubyDevKit (C:\RubyDevKit) installed.

I want to build a site with Middleman, and I found these articles by Ben Frain, Brett Klamer, and Tuts+.

When I type gem install middleman from C:/, it works. I can see middleman-cli-4.1.10 folder and middleman-core-4.1.10 folder in: C:\Ruby21\lib\ruby\gems\2.1.0\gems

And then I run middleman init my_site, it works too. Now, I have (in my_site folder): source, .gitignore, config.rb, config.ru, Gemfile, and Gemfile.lock.

But, everytime I run middleman server nor bundle exec middleman server, it gives me this:

WARN: Unresolved specs during Gem::Specification.reset:sass (>= 3.4)
WARN: Clearing out unresolved specs.
Please report a bug if this causes problems.
C:/Ruby21/lib/ruby/gems/2.1.0/gems/middleman-cli-4.1.10/bin/middleman:12:in`require':
cannot load such file -- dotenv (LoadError)from C:/Ruby21/lib/ruby/gems/2.1.0/gems/middleman-cli-4.1.10/bin/middleman:12:in `<top (required)>'
from C:/Ruby21/bin/middleman:22:in `load'
from C:/Ruby21/bin/middleman:22:in `<main>'

My question is, why does this happen? And how to solve this?

I think that I'm in the wrong folder when I run middleman init my_site. If so, then where should I run it? Am I need to run it in a special folder, or I can run it everywhere?

Thank you.

Rails Active Record to make arithmetic calculation over a select statement

I am trying to calculate values from existing table column and use it on an external variable.

Let my table columns be as : ["id","unit_price","quantity","extras_1","extras_2"] I am presenting what i want to do in rails using sql command as reference.

SQL Command:

SELECT unit_price*quantity AS "regular_price", 
       unit_price*quantity-unit_price*quantity*discount AS "price_after_discount"
FROM order_details;

In Rails Active Record Query i tried same as:

OrderDetail.select('unit_price*quantity AS regular_price,unit_price*quantity-unit_price*quantity*discount AS price_after_discount')

From the above query.i tried sorting based on derived attributes.it worked perfectly.But i cannot see the derived attribute values by querying.

The output i got is without the derived attributes as:

[#<OrderDetail >,#<OrderDetail >]

But i need output as:

[#<OrderDetail regular_price: 43, price_after_discount: 54>,#<OrderDetail regular_price: 54, price_after_discount: 76>]

I tried below query to sort the data.It sorted the data perfectly:

OrderDetail.select('unit_price,quantity,unit_price*quantity AS regular_price,unit_price*quantity-unit_price*quantity*discount AS price_after_discount').order('regular_price desc')

I can access the values using below command:

OrderDetail.select('unit_price,quantity,unit_price*quantity AS extras_1,unit_price*quantity-unit_price*quantity*discount AS extras_2')

above commmand worked because extras_1 and extras_2 are table columns.

But it is working when assigned to existing table column.I need derived attribute to be non-existing table column name.

How can i access a derived attributes values from a record.I can access them by assigning them to an existing table column.But i want the attributes name given how i want irrespective of table columns.

Is it possible to sort based on an arthimatic operation in Ruby on rails active record?

I want to order records based on two columns Arthimatic operation.

Ex: I has two columns on which I has to do an arthimatic operation and sort based on its value. Let the two fields be math, science and total.And table name is UserMark. Typically my query looks like this

UserMark.order('(math/total) desc')

This should order the UserMarks based on math/total operation.How could it be done in Ruby on rails?

mercredi 19 octobre 2016

OR in where clause when working with nested includes or joins with association

I have to use OR in where clause when working with nested includes with association. i have ruby query some thing as :

Inventory.includes(:category,:inventory_tiers,:modifiers=>[:modifier_measures,:modifier_tiers]).where(:categories => { category_tag: 'Dry'},:location_id =>12,:inventory_tiers => {:tier => 1}),modifiers:{category_tag:"Wet"},modifier_tiers:{tier:1})

in which where clause uses AND for all condition. but i want to use OR for last two condition something as :

Inventory.includes(:category,:inventory_tiers,:modifiers=>[:modifier_measures,:modifier_tiers]).where("categories.category_tag=? AND location_id=? AND inventory_tiers.tier = ? OR modifiers.category_tag=? OR modifier_tiers.tier=?", "Wet",12,1,"Wet",1).select("inventories.id,inventories.name,inventories.photo,inventory_tiers.sell_price, modifiers.id,modifiers.name,modifiers.price,modifier_measures.id as measure_id,modifier_measures.name as measure,modifier_measures.price as measure_price,modifier_measures.measure_value")

but its not working. how i can write ?.

Rails confuses loading of assets by js for actual route and processes it as controller action

I'm trying to implement ion.sound in Rails 3.22 I can't get to have the sounds to be processed. I parametered ion.sound to fetch the sound assets in "/app/assets", in my js.coffee file like this :

# initialise plugin for ion sound
$ -> $.ionSound
    sounds: [
       { name: 'metal_plate' }
    ]
    path: '/app/assets/'
    preload: true
    multiplay: true
    volume: 0.5
# play sound
$ -> $.ionSound.play 'metal_plate'

but I noticed that the server trace indicates that it is conducting GETs on the sound paths and that Rails processes theses assets paths as controller actions, attempting to execute the corresponding actions which don't exist. Here is an exemple from the trace:

Started GET "/app/assets/metal_plate.aac?1476881187282" for 127.0.0.1 at 2016-10-19 14:46:27 +0200 Processing by DimensionsController#show as Parameters: {"1476881187282"=>nil, "client_id"=>"app", "produit_id"=>"assets", "id"=>"metal_plate"} Redirected to http://ift.tt/2ehZknD Filter chain halted as :signed_in_client rendered or redirected

so the result is a useless redirection and the sound asset isn't processed by ion.sound... What a mess !

rails multiple table id find

and use rails polymorphic association..

This is wall_notification.rb

class WallNotification < ActiveRecord::Base
    belongs_to :attachable, polymorphic: true
    belongs_to :user
end

This is picture.rb

class Picture < ActiveRecord::Base
    belongs_to :user
    has_many :wall_notifications, as: :attachable
    mount_uploader :pic_upload
    validates :pic_upload,presence: true
end

This is user_video.rb

class UserVideo < ActiveRecord::Base
    belongs_to :user
    has_many :wall_notifications, as: :attachable
    mount_uploader :user_video
end

This is career.rb

class Career < ActiveRecord::Base
    has_many :wall_notifications, as: :attachable
    mount_uploader :career_file
end

and,when create new picture,user_video,career, wall_notifiacatin will create new record automatically because,we use polymorphic association..

when i check my rails console..polymorphic association perfectly working..

[1] pry(main)> WallNotification.all
  WallNotification Load (220.3ms)  SELECT `wall_notifications`.* FROM `wall_notifications`
=> [#<WallNotification:0xb4b51d0
  id: 1,
  user_id: 1,
  attachable_id: 1,
  attachable_type: "Picture",
  created_at: Wed, 19 Oct 2016 04:50:55 UTC +00:00,
  updated_at: Wed, 19 Oct 2016 04:50:55 UTC +00:00>,
 #<WallNotification:0xb4a98e4
  id: 2,
  user_id: 1,
  attachable_id: 1,
  attachable_type: "UserVideo",
  created_at: Wed, 19 Oct 2016 04:53:43 UTC +00:00,
  updated_at: Wed, 19 Oct 2016 04:53:43 UTC +00:00>,
 #<WallNotification:0xb4a9740
  id: 3,
  user_id: 1,
  attachable_id: 1,
  attachable_type: "Career",
  created_at: Wed, 19 Oct 2016 05:12:43 UTC +00:00,
  updated_at: Wed, 19 Oct 2016 05:12:43 UTC +00:00>]

but now i want to current_user's wall_notifications list..and this is my controller.rb

def index
    @wall_notifications_picture = current_user.wall_notifications.where(attachable_type: 'Picture')
    @picture_ids = @wall_notifications_picture.map {|w| Picture.find_by_id(w.attachable_id)}
    @wall_notifications_uservideo = current_user.wall_notifications.where(attachable_type: 'UserVideo')
    @uservideo_ids = @wall_notifications_uservideo.map {|w| UserVideo.find_by_id(w.attachable_id)}
    @wall_notifications_career = current_user.wall_notifications.where(attachable_type: 'Career')
    @career_ids = @wall_notifications_uservideo.map {|w| Career.find_by_id(w.attachable_id)}
   end

i want each table data in one instance variable :( :( Any one help me..

mardi 18 octobre 2016

How and where can I import a common SCSS files, so that it gets available in every scss files?

I have scss files that use variables for colors. like -

.label-primary, .badge-primary {
  background-color: $navy;
  color: #FFFFFF;
}

.label-success, .badge-success {
  background-color: $blue;
  color: #FFFFFF;
}

.label-warning, .badge-warning {
  background-color: $yellow;
  color: #FFFFFF;
}

These variables are defined in variables.scss file

I have already @imported @import "base/variables"; in application.css.scss file.

// Variables, Mixins
@import "base/variables";
@import "base/mixins";

but still it doesnt loads in other scss files and throws error Sass::SyntaxError: Undefined variable: "$navy". where trying to precompile in production.

I have to explicitely @import "base/variables"; in every scss file on the top. there are 35 files.

How can i define this variable.scss file in just one place so that its loaded in every scss file?

NOTE: I am using rails-api gem and the application is API only. I have tweaked a bit to make some views on this application.

rake db:migrate does not create table

I'm using Rails 4.2.6 and have strange error (learning rails with the HeadFirst book, project and directory name - "mebay"):

I need to create project uses only "read" of CRUD - so I run:

~/mebay $ rails generate model ad name:string description:text price:decimal seller_id:integer email:string img_url:string

Running via Spring preloader in process 8400
      invoke  active_record
   identical    db/migrate/20161018144410_create_ads.rb
   identical    app/models/ad.rb
      invoke    test_unit
   identical      test/models/ad_test.rb
   identical      test/fixtures/ads.yml

and here comes my db/migrate/20161018144410_create_ads.rb:

class CreateAds < ActiveRecord::Migration
  def change
    create_table :ads do |t|
      t.string :name
      t.text :description
      t.decimal :price
      t.integer :seller_id
      t.string :email
      t.string :img_url

      t.timestamps null: false
    end
  end
end

(looks pretty ok for me, basing on earlier projects)

Then, as I understand, I need to create database (i use sqlite):

~/mebay $ rake db:migrate

but after that, my development.sqlite3 remain empty

what am i doing wrong?

What's the easiest way to edit a dependency in a gem stored on GitHub

I'm trying to install a gem from GitHub, but in the gemspec a dependency version makes installing the gem impossible. All I need is to edit that version.

What's the easiest way of doing this so I can make the gem usable in my app ?

Cannot modify association ":has_many." using Ruby on rails

I'm working with three tables as follows:

article.rb

class Article < ActiveRecord::Base
  has_many :comments
  has_many :comentarios, :through => :comments
end

comment.rb

class Comment < ActiveRecord::Base
  belongs_to :article
  has_many :comentarios 
end

and comentario.rb

class Comentario < ActiveRecord::Base
  belongs_to :article
end

Everything works fine until I attempt to add a 'comentario' and returns this error

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection in ComentariosController#create 
Cannot modify association 'Article#comentarios' because the source reflection class 'Comentario' is associated to 'Comment' via :has_many.

This is the code I use to create a new 'comentario'

comentarios_controller.rb

class ComentariosController < ApplicationController

  def new
      @comentario = Comentario.new
  end

  def create
   @article = Article.find(params[:article_id])
   @comentario = @article.comentarios.create(comentario_params)
   redirect_to article_path(@article)
 end

 private
   def comentario_params
     params.require(:comentario).permit(:comentador, :comentario)
   end
end

The output returns an error in the line where I create @comentario from calling @article but I can't see why since Ruby documentation says that once I associate comentario to article using :through, I can simply call something like @article.comentario.

Any idea of what is causing this error? or do you have any suggestion on how to achieve this association in any other way?

Javasript does not work after j rendering a view

When I dynamically update content to a page using a remote call and a *js.erb file like this:

add_content.js.erb

$("#new_content").html('<%= j render("content") %>');

To render a view like this: _content.html.erb

<div class="name">
    <%= @content.name %>
</div>
<div class="text">
    <%= @content.text %>
</div>

With an javasript file like this: application.js

$(".name").on('click', function(){
  $(".text").slideToggle();
});

... the javascript slideToggle() is not executed. When I do

<%= render("content") %> 

in any view (without js.erb) everything works as expected and slideToggle() works. This is just a quick example to keep it simple, it is not related to slideToggle, even alert("...") etc. will not work.

So my question is why is javascript not executed? Is this related to any loading order?

How can I do something like this with ruby arrays

I have an user array like this:

users_array = [[1,text for 1],[2,text for 2],[3,text for 3],[4,text for 4],[5,text for 5]]

here first element is user_id and second element is text which is specific to user_id in the same array.

Now I am trying to have user object from instead of ids in array like these.

users_array = [[#<User id: 1, encrypted_email: "">,text for 1],[#<User id: 2, encrypted_email: "">,text for 2],[#<User id: 3, encrypted_email: "">,text for 3],[#<User id: 4, encrypted_email: "">,text for 4],[#<User id: 5, encrypted_email: "">,text for 5]]

I am trying not to loop the array and hit the db thousand times for thousands user.

lundi 17 octobre 2016

Rails facebook messenger bot heroku error

I am building an messenger bot on rails and firstly i want to say hello. For do that

1- I am following these instruction(http://ift.tt/26Guj10)

2- Then i am using heroku for putting my app on the web. So get error when i do this.

This is my bot.rb file under app/bot/bot.rb

require 'facebook/messenger'

include Facebook::Messenger

Bot.on :message do |message|
  message.id          # => 'mid.1457764197618:41d102a3e1ae206a38'
  message.sender      # => { 'id' => '1008372609250235' }
  message.seq         # => 73
  message.sent_at     # => 2016-04-22 21:30:36 +0200
  message.text        # => 'Hello, bot!'
  message.attachments # => [ { 'type' => 'image', 'payload' => { 'url' => 'http://ift.tt/2efcRdZ' } } ]

  Bot.deliver(
    recipient: message.sender,
    message: {
      text: 'Hello, human!'
    }
  )

Bot.on :postback do |postback|
  postback.sender    # => { 'id' => '1008372609250235' }
  postback.recipient # => { 'id' => '2015573629214912' }
  postback.sent_at   # => 2016-04-22 21:30:36 +0200
  postback.payload   # => 'EXTERMINATE'

  if postback.payload == 'EXTERMINATE'
    puts "Human #{postback.recipient} marked for extermination"
  end
end

Bot.on :optin do |optin|
  optin.sender    # => { 'id' => '1008372609250235' }
  optin.recipient # => { 'id' => '2015573629214912' }
  optin.sent_at   # => 2016-04-22 21:30:36 +0200
  optin.ref       # => 'CONTACT_SKYNET'

  Bot.deliver(
    recipient: optin.sender,
    message: {
      text: 'Ah, human!'
    }
  )
end

Bot.on :delivery do |delivery|
  delivery.ids       # => 'mid.1457764197618:41d102a3e1ae206a38'
  delivery.sender    # => { 'id' => '1008372609250235' }
  delivery.recipient # => { 'id' => '2015573629214912' }
  delivery.at        # => 2016-04-22 21:30:36 +0200
  delivery.seq       # => 37

  puts "Human was online at #{delivery.at}"
end

I am getting these error at my heroku app

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

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

This is my result of heroku logs

2016-10-17T17:37:55.770669+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/application/finisher.rb:59:in `block in <module:Finisher>'
2016-10-17T17:37:55.770726+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'
2016-10-17T17:37:55.770696+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `instance_exec'
2016-10-17T17:37:55.770711+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `run'
2016-10-17T17:37:55.770741+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
2016-10-17T17:37:55.770756+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
2016-10-17T17:37:55.770786+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
2016-10-17T17:37:55.770771+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
2016-10-17T17:37:55.770843+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
2016-10-17T17:37:55.770815+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `call'
2016-10-17T17:37:55.770801+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `each'
2016-10-17T17:37:55.770868+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
2016-10-17T17:37:55.770884+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
2016-10-17T17:37:55.770898+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:54:in `run_initializers'
2016-10-17T17:37:55.770913+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:352:in `initialize!'
2016-10-17T17:37:55.770929+00:00 app[web.1]:    from /app/config/environment.rb:5:in `<top (required)>'
2016-10-17T17:37:55.770944+00:00 app[web.1]:    from config.ru:3:in `require_relative'
2016-10-17T17:37:55.770959+00:00 app[web.1]:    from config.ru:3:in `block in <main>'
2016-10-17T17:37:55.770974+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `instance_eval'
2016-10-17T17:37:55.770989+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `initialize'
2016-10-17T17:37:55.771019+00:00 app[web.1]:    from config.ru:in `new'
2016-10-17T17:37:55.771047+00:00 app[web.1]:    from config.ru:in `<main>'
2016-10-17T17:37:55.771077+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:49:in `new_from_string'
2016-10-17T17:37:55.771062+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:49:in `eval'
2016-10-17T17:37:55.771093+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:40:in `parse_file'
2016-10-17T17:37:55.771107+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/configuration.rb:315:in `load_rackup'
2016-10-17T17:37:55.771122+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/configuration.rb:243:in `app'
2016-10-17T17:37:55.771137+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/runner.rb:127:in `load_and_bind'
2016-10-17T17:37:55.771152+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/single.rb:85:in `run'
2016-10-17T17:37:55.771167+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/launcher.rb:172:in `run'
2016-10-17T17:37:55.771195+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/cli.rb:74:in `run'
2016-10-17T17:37:55.771222+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/bin/puma:10:in `<top (required)>'
2016-10-17T17:37:55.771238+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/bin/puma:23:in `load'
2016-10-17T17:37:55.771253+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/bin/puma:23:in `<main>'
2016-10-17T17:37:55.899711+00:00 heroku[web.1]: Process exited with status 1
2016-10-17T17:37:55.892951+00:00 heroku[web.1]: State changed from starting to crashed
2016-10-17T17:43:28.389559+00:00 heroku[web.1]: State changed from crashed to starting
2016-10-17T17:43:31.094495+00:00 heroku[web.1]: Starting process with command `bundle exec puma -C config/puma.rb`
2016-10-17T17:43:33.892184+00:00 app[web.1]: Puma starting in single mode...
2016-10-17T17:43:33.892202+00:00 app[web.1]: * Version 3.6.0 (ruby 2.3.1-p112), codename: Sleepy Sunday Serenity
2016-10-17T17:43:33.892203+00:00 app[web.1]: * Min threads: 5, max threads: 5
2016-10-17T17:43:33.892205+00:00 app[web.1]: * Environment: production
2016-10-17T17:43:35.493955+00:00 app[web.1]: ! Unable to load application: SyntaxError: /app/app/bot/bot.rb:53: syntax error, unexpected end-of-input, expecting keyword_end
2016-10-17T17:43:35.493990+00:00 app[web.1]: /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:263:in `rescue in load_dependency': /app/app/bot/bot.rb:53: syntax error, unexpected end-of-input, expecting keyword_end (SyntaxError)
2016-10-17T17:43:35.494011+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:256:in `load_dependency'
2016-10-17T17:43:35.494012+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:293:in `require'
2016-10-17T17:43:35.494012+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:380:in `block in require_or_load'
2016-10-17T17:43:35.494013+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:37:in `block in load_interlock'
2016-10-17T17:43:35.494015+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies/interlock.rb:12:in `block in loading'
2016-10-17T17:43:35.494016+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/concurrency/share_lock.rb:117:in `exclusive'
2016-10-17T17:43:35.494017+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies/interlock.rb:11:in `loading'
2016-10-17T17:43:35.494018+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:37:in `load_interlock'
2016-10-17T17:43:35.494019+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:358:in `require_or_load'
2016-10-17T17:43:35.494033+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:336:in `depend_on'
2016-10-17T17:43:35.494034+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/activesupport-5.0.0.1/lib/active_support/dependencies.rb:252:in `require_dependency'
2016-10-17T17:43:35.494035+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:476:in `block (2 levels) in eager_load!'
2016-10-17T17:43:35.494037+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:475:in `each'
2016-10-17T17:43:35.494039+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:475:in `block in eager_load!'
2016-10-17T17:43:35.494041+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:473:in `each'
2016-10-17T17:43:35.494041+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:473:in `eager_load!'
2016-10-17T17:43:35.494042+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/engine.rb:354:in `eager_load!'
2016-10-17T17:43:35.494055+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/application/finisher.rb:59:in `each'
2016-10-17T17:43:35.494056+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/application/finisher.rb:59:in `block in <module:Finisher>'
2016-10-17T17:43:35.494058+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `instance_exec'
2016-10-17T17:43:35.494058+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:30:in `run'
2016-10-17T17:43:35.494059+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:55:in `block in run_initializers'
2016-10-17T17:43:35.494073+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
2016-10-17T17:43:35.494073+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
2016-10-17T17:43:35.494075+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
2016-10-17T17:43:35.494075+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
2016-10-17T17:43:35.494077+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `each'
2016-10-17T17:43:35.494078+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `call'
2016-10-17T17:43:35.494079+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
2016-10-17T17:43:35.494092+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
2016-10-17T17:43:35.494092+00:00 app[web.1]:    from /app/vendor/ruby-2.3.1/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
2016-10-17T17:43:35.494093+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/initializable.rb:54:in `run_initializers'
2016-10-17T17:43:35.494095+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/railties-5.0.0.1/lib/rails/application.rb:352:in `initialize!'
2016-10-17T17:43:35.494097+00:00 app[web.1]:    from /app/config/environment.rb:5:in `<top (required)>'
2016-10-17T17:43:35.494098+00:00 app[web.1]:    from config.ru:3:in `require_relative'
2016-10-17T17:43:35.494099+00:00 app[web.1]:    from config.ru:3:in `block in <main>'
2016-10-17T17:43:35.494112+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `instance_eval'
2016-10-17T17:43:35.494112+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:55:in `initialize'
2016-10-17T17:43:35.494113+00:00 app[web.1]:    from config.ru:in `new'
2016-10-17T17:43:35.494115+00:00 app[web.1]:    from config.ru:in `<main>'
2016-10-17T17:43:35.494116+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:49:in `eval'
2016-10-17T17:43:35.494130+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:49:in `new_from_string'
2016-10-17T17:43:35.494159+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/rack-2.0.1/lib/rack/builder.rb:40:in `parse_file'
2016-10-17T17:43:35.494160+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/configuration.rb:315:in `load_rackup'
2016-10-17T17:43:35.494160+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/configuration.rb:243:in `app'
2016-10-17T17:43:35.494161+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/runner.rb:127:in `load_and_bind'
2016-10-17T17:43:35.494163+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/single.rb:85:in `run'
2016-10-17T17:43:35.494164+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/launcher.rb:172:in `run'
2016-10-17T17:43:35.494165+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/lib/puma/cli.rb:74:in `run'
2016-10-17T17:43:35.494166+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/gems/puma-3.6.0/bin/puma:10:in `<top (required)>'
2016-10-17T17:43:35.494168+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/bin/puma:23:in `load'
2016-10-17T17:43:35.494168+00:00 app[web.1]:    from /app/vendor/bundle/ruby/2.3.0/bin/puma:23:in `<main>'
2016-10-17T17:43:35.626538+00:00 heroku[web.1]: State changed from starting to crashed
2016-10-17T17:43:35.613367+00:00 heroku[web.1]: Process exited with status 1
2016-10-17T17:51:06.046403+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=glacial-woodland-33867.herokuapp.com request_id=40aae514-ece3-4d20-80ec-ed54aea9000e fwd="95.70.128.173" dyno= connect= service= status=503 bytes=
2016-10-17T17:51:06.752064+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=glacial-woodland-33867.herokuapp.com request_id=9d9eb0c1-c46b-42c8-8775-4e8349afea2e fwd="95.70.128.173" dyno= connect= service= status=503 bytes=
2016-10-17T17:51:30.850595+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=glacial-woodland-33867.herokuapp.com request_id=7e8fcd04-4aec-477e-a166-2fa02c554f2c fwd="95.70.128.173" dyno= connect= service= status=503 bytes=

Rials 4, SQ Lite 3: NoMethodError - undefined method: nil:NilClass

I've created a Notification Model which belongs_to a User (Devise) and each User has_many Notifications.
However I somehow can't get the Notifications in my Applications Controller or any other Controller:

def notifications
    @notifications = current_user.notifications.order('created_at desc')
end

I always seem to get nil as Object.

For example:
Recipes / Search View:

- if @notifcations.exists?

gives me this error:

NoMethodError
undefined method `exists?' for nil:NilClass

Thanks in advance for any help!

dimanche 16 octobre 2016

Rails bug in Active Record Model

I was practicing my Code and soon I found that '.order' method works in reverse. My rails version is '5.0.0.1'

I used it like:

(i) User.order(salary: :desc).first(3)

(ii) User.order(salary: :desc).first(3)

I got reverse results. I am using mysql database. Can anybody tell me whether its mine mistake or really it's rails problem.

samedi 15 octobre 2016

undefined method `empty?` for nil:NilClass

When I was trying to run rake db:migrate on this open source project called expertiza (link:http://ift.tt/2dSRU9X), I got this error message. The full message is showing below. I think the problem is probably something wrong with the environment set up. Is there any way to fix this bug without changing the code?

Error message:

rake aborted!

StandardError: An error has occurred, all later migrations canceled:

undefined method `empty?' for nil:NilClass
/home/maxinghua/expertiza/app/models/menu.rb:81:in `initialize'
/home/maxinghua/expertiza/app/models/role.rb:87:in `new'
/home/maxinghua/expertiza/app/models/role.rb:87:in `rebuild_menu'
/home/maxinghua/expertiza/app/models/role.rb:73:in `block in rebuild_cache'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `block (2 levels) in find_each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `block in find_each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:124:in `find_in_batches'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:50:in `find_each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/querying.rb:9:in `find_each'
/home/maxinghua/expertiza/app/models/role.rb:67:in `rebuild_cache'
/home/maxinghua/expertiza/db/migrate/002_initialize_custom.rb:184:in `up'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:571:in `up'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:611:in `exec_migration'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:591:in `block in migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:590:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:768:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:1046:in `ddl_transaction'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:959:in `block in migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:823:in `up'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:801:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/tasks/database_tasks.rb:137:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/airbrake-5.5.0/lib/airbrake/rake/task_ext.rb:19:in `execute'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/rake-11.2.2/exe/rake:27:in `<top (required)>'
/home/maxinghua/.rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `eval'
/home/maxinghua/.rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `<main>'
NoMethodError: undefined method `empty?' for nil:NilClass
/home/maxinghua/expertiza/app/models/menu.rb:81:in `initialize'
/home/maxinghua/expertiza/app/models/role.rb:87:in `new'
/home/maxinghua/expertiza/app/models/role.rb:87:in `rebuild_menu'
/home/maxinghua/expertiza/app/models/role.rb:73:in `block in rebuild_cache'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `block (2 levels) in find_each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `block in find_each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:124:in `find_in_batches'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:50:in `find_each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/querying.rb:9:in `find_each'
/home/maxinghua/expertiza/app/models/role.rb:67:in `rebuild_cache'
/home/maxinghua/expertiza/db/migrate/002_initialize_custom.rb:184:in `up'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:571:in `up'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:611:in `exec_migration'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:591:in `block in migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:590:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:768:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:1046:in `ddl_transaction'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:959:in `block in migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `each'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:823:in `up'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:801:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/tasks/database_tasks.rb:137:in `migrate'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/airbrake-5.5.0/lib/airbrake/rake/task_ext.rb:19:in `execute'
/home/maxinghua/.rvm/gems/ruby-2.2.4/gems/rake-11.2.2/exe/rake:27:in `<top (required)>'
/home/maxinghua/.rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `eval'
/home/maxinghua/.rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

This is the reported 'empty?' method Code in menu.rb:81:in `initialize':

if role
  unless role.cache[:credentials].permission_ids.empty?
    items = MenuItem.items_for_permissions(role.cache[:credentials].permission_ids)
  end
else # No role given: build menu of everything
  items = MenuItem.items_for_permissions
end

Get and display all values from database row separately based on select (Rails)

Hi i'm stuck making an invoicing application and i want to have an option where you can add an existing user from the customers table and add those values to the invoice.

The values i want to display are company_name, vat_number and iban_number.

I tried doing this:

<%= select_tag 'choose customer', options_from_collection_for_select(current_user.companies.all, 'id', 'company_name') %>

But obviously this only gets the value of company_name.

I tried using collection.select but that one also gets only one value of the database row instead of all 3.

I want to be able to select from a list or table row containing just the company_name but when i click on that company_name it has to also display vat_number and iban_number.

Any ideas on how to achieve this or where to look for the answer would be much much appreciated

vendredi 14 octobre 2016

how to convert my view table into excel format

I am new in ruby on rails, I want to export my view table in excel format, I have tried so many times but I can not able to export view table. I have a view (Employee_Information) in my database and all data displaying into view.html.erb page, there is no specific model for Employee_Information view. I have follow this tutorial "http://ift.tt/MmX2RS", but I this tutorial export data into excel from view table with the help of model, I want to with out model.

**excel_file.html.erb**
`<table border=1>
  <tr>
    <th>Employee ID</th>
    <th>Name</th>
    <th>Gender</th>
    <th>Date of birth</th>
    <th>Email</th>
    <th>Marital status</th>
    <th>Father Name</th>
    <th>Spouse Name</th>
    <th>Contact</th>
    <th>Employee Address</th>
    <th>Account Number</th>
    <th>IFSC Code</th>
    <th>PAN Number</th>
    <th>Client Name</th>
    <th>Designation</th>
    <th>Employee Type</th>
    <th>Status</th>
    <th>Joining date</th>
    <th>End date</th>
    <th>Offer CTC</th>
    <th>Client Address</th>    
  </tr>
  <% @employees.each do |emp| %>   
    <tr>
       <th><%= emp['employee_id'] %></th>
        <th><%= emp['full_name'] %></th>
        <th><%= emp['gender'] %></th>
        <th><%= emp['dob_date'] %></th>
        <th><%= emp['email'] %></th>
        <th><%= emp['married_status'] %></th>
        <th> <%= emp['father_name'] %></th>
        <th><%= emp['spouse_name'] %></th>
        <th><%= emp['contact_phone'] %></th>
        <th><%= emp['candidate_address2'] %></th>
        <th><%= emp['bank_ac'] %></th>
        <th><%= emp['bank_ifsc'] %></th>
        <th><%= emp['pan_number'] %></th>
        <th><%= emp['company_name'] %></th>
        <th><%= emp['designation'] %></th>
        <th>
            <% if emp['employee_type'] == 0 %>
                Internal Employee
            <% elsif emp['employee_type'] == 1 || emp['employee_type'] == 2 || emp['employee_type'] == 3 %>
                Contract Consultant Employee
            <% elsif emp['employee_type'] == 4 %>
                Permanent Consultant Employee
            <% elseif emp['employee_type'] == 5 %>
                Past Employee
            <% end %> 
        </th>
        <th>
            <% if emp['status'] == 0 %>
                Pending
            <% elsif emp['status'] == 1 %>
                Approved
            <% elsif emp['status'] == 2 %>
                Cancelled
            <% elsif emp['status'] == 3 %>
                Accepted
            <% elsif emp['status'] == 4 %>
                Rejected
            <% elsif emp['status'] == 5 %>
                Onboarded
            <% elsif emp['status'] == 6 %>
                Offboarded
            <% end %> 
        </th>
        <th><%= emp['joining_date'] %></th>
        <th><%= emp['work_end_date'] %></th>
        <th><%= emp['ctc'] %></th>
        <th><%= emp['client_address2']%></th>  
    </tr>
  <% end %>  
</table>
<br><br>`

**hr_controller.rb**`def excel_file
        @employees = MysqlConnection.connection.select_all("SELECT * FROM         Employee_Information where employee_type IN(0)")
        #@employees = MysqlConnection.connection.select_all("SELECT * FROM Employee_Information where employee_type IN(1,2,3)")
        respond_to do |format|
            format.html
            format.csv { send_data @employees.to_csv }
        end
    end`
**application.rb**



  require File.expand_path('../boot', __FILE__)
     # add HR role
     require "csv"

I have created a file module "employee_information.rb" into lib folder

  module EmployeeInformation    
      def self.to_csv(options = {})
        CSV.generate(options) do |csv|
            csv << column_names
            all.each do |product|
              csv << product.attributes.values_at(*column_names)
            end
        end
    end end