samedi 30 juillet 2016

ArgumentError in ContactsController#new

I am getting error while i visit to the page localhost:3000/contacts
error of detials and source code is provided below.

wrong number of arguments (1 for 2)

Extracted source (around line #4):

2  attribute :name,      :validate => true
3  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
4  attribute :message
5  attribute :nickname,  :captcha => true

here is code of model

class Contact < ApplicationRecord
  attribute :name,      :validate => true
  attribute :email,     :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i
  attribute :message
  attribute :nickname,  :captcha => true

  # Declare the e-mail headers. It accepts anything the mail method
  # in ActionMailer accepts.
  def headers
    {
      :subject => "HsbNoid",
      :to => "iamhsb001@gmail.com",
      :from => %("#{name}" <#{email}>)
    }
  end
end

here is code for controller

class ContactsController < ApplicationController
     def new
    @contact = Contact.new
  end
  def create
    @contact = Contact.new(conact_params)
    @contact.request = request
    if @contact.deliver
      flash.now[:notice] = 'Thank you for your message. We will contact you soon!'
    else
      flash.now[:error] = 'Cannot send message.'
      render :new
    end
  end
  private
  def conact_params
    params.require(:contact).permit(:name, :email, :message)
  end
end

uninitialized constant ActiveModel::Observing (NameError)

I have developed a web application using ruby on rails. I have upgraded my rails version from 3.2 to 4.0 and I am getting the below error while starting my server.

Error :

/home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:11:in <module:Config>': uninitialized constant ActiveModel::Observing (NameError) from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:8:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid/config.rb:5:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/dynamoid-0.6.1.1/lib/dynamoid.rb:21:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:76:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:76:inblock (2 levels) in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:74:in each' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:74:inblock in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:63:in each' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runtime.rb:63:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/bundler-1.3.5/lib/bundler.rb:132:in require' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config/application.rb:88:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config/environment.rb:6:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:inrequire' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in require' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:3:inblock in ' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:55:in instance_eval' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:55:ininitialize' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:in new' from /home/lakhwani/FCLaunchRequirement/src/FCLaunchRequirementWebsite/rails-root/config.ru:in' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:49:in eval' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:49:innew_from_string' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/builder.rb:40:in parse_file' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:277:inbuild_app_and_options_from_config' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:199:in app' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:314:inwrapped_app' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:250:in start' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/lib/rack/server.rb:141:instart' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/ruby1.9/gems/1.9.1/gems/rack-1.5.2/bin/rackup:4:in <top (required)>' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/bin/rackup:23:inload' from /home/lakhwani/FCLaunchRequirement/env/FCLaunchRequirementWebsite-1.0/runtime/bin/rackup:23:in <main>' /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/ruby2.1.x/lib/ruby/site_ruby/2.1.0/amazon/brazil/ruby.rb:98:inexec_build_script': Command exited with status 1!! (RuntimeError) from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:61:in block in <main>' from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:48:ineach' from /home/lakhwani/FCLaunchRequirement/env/BrazilRake-1.1/runtime/bin/brazilrake:48:in `'

Can any one help me resolve this issue?

How can i take a cut/commission in paypal?

how can i take a cut/commission in paypal after user has paid amount and before receiver has got amount.

In my application I allow sellers to give some service to customers. When a customer pays $100 to seller then I need to cut 12.5% as commission.

How can I do that in Paypal. My Application is in rails.

how to display json and parse json in ruby using httparty

I am working on a food app in ruby on rails which requires to get calorie value of food item from food api.In my controller i am getting the JSON response but i am unable to parse and display the calorie value of food item in a index.html.erb file here is my controller code.

require 'rubygems'

require 'httparty'

class FoodsController < ApplicationController

def index @foods = Food.all end

def show @food = Food.find(params[:id]) end

def new @food = Food.new

end

def edit @food = Food.find(params[:id]) end

def create @food = Food.new(food_params)

@response = HTTParty.get('http://ift.tt/2aRHDbB'+@food.name+'?fields=item_name%2Citem_id%2Cbrand_name%2Cnf_serving_size_unit%2Cnf_calories%2Cnf_total_fat&appId=696d1ad4&appKey=aec2c4766d40d7f6346ed89d5d82fe75')
@http_party_json = JSON.parse(@response.body)

if @food.save redirect_to foods_path else render 'new' end end

def update @food = Food.find(params[:id])

if @food.update(food_params) redirect_to @food else render 'edit' end end

def destroy @food = Food.find(params[:id]) @food.destroy

redirect_to foods_path

end

private def food_params params.require(:food).permit(:name, :quantity) end

end

Any suggestions are highly welcome as i am newbie on stackoverflow so dont know proper editing forgive please! help me how to display calorie value in html page

vendredi 29 juillet 2016

activeRecord::ConnectionNot Established No connection pool with id primary found: mysql2

im very new to ruby on rails. and learning ruby on rails by a tutorials: Lynda.com - Ruby on Rails 4 Essential Training with kavin skoglund. all was going fine, unttil, i run my application first time which means "http://localhost:3000" i get this error: activeRecord::ConnectionNotEstablished No connection pool with id primary found.

im using Rails 5.0.0 ruby 2.3.1 mysql2

it is completely configure in Gemfile and config\database.yml.

if I go for splite3 to solve this problem, then i can not follow this tutorial. can anyone help me to solve this issue while i have mysql2 as my database. Adeel Ahmed. http://adeelahmed.net

jeudi 28 juillet 2016

Savon 2.11.1 set soap header after client is instantiated Rails + SSRS

I'm trying to integrate my rails app with a Sql Server Reports Services (SSRS) using Savon 2.11.1. I'm using the ReportServicesExecution2005 WSDL. The problem I have is that I have to add a session_id to the soap header after the client has been instantiated. This is because the session_id is generated by SSRS after the client makes a call to load_report.

client = Savon.client(wsdl: "http://ift.tt/2agxWl8", basic_auth: ["user", "pass"])

this call returns the session_id in the response:

response = client.call(:load_report, message: {report: "path/to/report"} ) 

the soap header needs to contain the session_id in the client when this call is made:

client.call(:set_execution_parameters, message: { report: "path/to/report", parameters: params  }  )

Tried this but it didn't work:

client.call(:set_execution_parameters, soap_header: {"session_id" => @session_id}, message: { report: "path/to/report", parameters: params  }  ) 

I get the following error:

(soap:Client) The session identifier is missing. A session identifier is required for this operation. ---> Microsoft.ReportingServices.Diagnostics.Utilities.MissingSessionIdException: The session identifier is missing. A session identifier is required for this operation.

Thanks for the help an advance.

LoadError enc/trans/single_byte.so

I receive the following error when attempting to do string.encode("UTF-8") with a non-ascii character.

LoadError: dlopen(enc/trans/single_byte.so, 9): image not found - enc/trans/single_byte.so

Unlike the answer here, it appears that this file does not exist in my ruby install, or anywhere else on the system for that matter. I'm running ruby 2.1.7 and bundler 1.10.6, running on Mac OSX 10.11.5. I tried reinstalling ruby (using RVM) with no success.

Should this file exist, and if so what do I need to install?

mercredi 27 juillet 2016

Why "accepts_nested_attributes_for" is not working?

I have following models

Order

    class Order < ApplicationRecord
         has_many  :items
         accepts_nested_attributes_for :items
    end

and Item

class Item < ApplicationRecord


belongs_to  :order

end

And I have following Json to parse where an order contains multiple items

    {
  "location": "takeAway",
  "status": "preparing",
  "items": [
    {
        "id":2,
      "name": "coffee",
      "quantity": 1,
      "milk": "whole",
      "size": "small"
    }
  ]
}

And I have following code my controller.

 params.require(:order).permit(:location, :status, items_attributes:  [:id, :name, :quantity, :milk, :size])

Why I am not able to save Order records with item records? Can someone please help?

How can you make the id in the URL be random?

So I am looking for a way to create a randomized id that will link to a lobby that will be shown when the shown method is called in rails. As of right now, the url would look like this: http://localhost:3000/lobby/2. I'm looking to replace that 2 with a randomly generated id so you could send that link to friends if you want them to join your lobby. Any ideas?

the carrousel dont works , it dont show the images

I am using the theme oxygen : (http://ift.tt/29ZTh77) in my rails project , I am new in rails and front-end and dont know a lot about it. The problem is that the carrousel dont show the image ,it work well about the moves ,but the image dont works. I would like to know the correct way to link the image , the way that the theme makes is:

 <div class="item active" style="background-image: url(images/slider/1.jpg)">
          <div class="caption">
            <h1 class="animated fadeInLeftBig">Esta é a  <span>VôA Studio Tech</span></h1>
            <p class="animated fadeInRightBig"><h3>"Ascenda sua ideias "</h3></p>
            <a data-scroll class="btn btn-start animated fadeInUpBig" href="#services">Start now</a>
          </div>
        </div>

I tried to use this way,but did not works too:

 <div class="item active" style="background-image: <%image_tag(1.png)%>">
          <div class="caption">
            <h1 class="animated fadeInLeftBig">Esta é a  <span>VôA Studio Tech</span></h1>
            <p class="animated fadeInRightBig"><h3>"Ascenda sua ideias "</h3></p>
            <a data-scroll class="btn btn-start animated fadeInUpBig" href="#services">Start now</a>
          </div>
        </div>

Someone can help me?

how can if shortened with the same satisfying condition

How can I shroten the condition because it has the same satisfying that greater than zero. Here is the code below:

a = 10
b = 5
c = 2

if a > 0 || b > 0 || c > 0
  puts "greater that zero"
else
  puts "it is zero or less than zero"
end

mardi 26 juillet 2016

Minimize nested loops

I have the following code with nested loops. How can I minimize the loop?

users result is like:

=> [[35, 61, 62, 63, 64, 65, 66, 67, 68, 69, nil, 70, 71, 72, 73, 74, 75, 78, 79, 92, 94, 95, 154, 164, 292, 293, 294, 295, 314], [], [35], [], [35, 79, 88], [], [], [36, 35, 56, 78, 87, 95, 65], [63, 72, 78, 80, 81, 82, 84, 87, 90, 93, nil, 96, 111, 157, 159, 160, 271, 272, 66, 295, 296, 297, 298, 299, 300, 301, 305, 307, 308, 71, 315], [], [79, 83, 85, 86, 89, 91, 161, 162, 163, 67, 294, 302, 303, 304, 306, 309, 310, 311, 312, 313], [], [314], [314], []]

That's why I need to loop the object in each elements.

And array value is:

=> [309, 310, 305, 304, 90, 162, 78, 297, 296, 272, 271, 84, 91, 308, 299, 79, 87, 298, 301, 163, 81, 72, 83, 111, 86, 313, 164, 300, 159, 315, 160, 307, 82, 69, 312, 89]

Thanks!

0.upto(users.count).each do |i|
  users[i].each do |user_id|
    if array.include?(user_id)
      puts user_id
    end
  end
end

RoR in Windows not working for pre-existing app built with RoR in linux

I've installed Ruby on Rails using RailsInstaller and also postgresql in Windows 8. I'm trying to run rails server using files for a pre existing app but I'm getting the error 'Worker mode not supported on JRuby or Windows'.

In my config/puma.rb file i've set workers to 0, then get an error about daemon mode not supported on windows. basically each time i change something i get more errors.

I've fixed up environment variables, gems, etc (like in other posts) such as this Cannot install Puma gem on Ruby on Rails. there any hope of running a pre-existing RoR app built in linux on a windows machine?

When I run rails server for the RoR 'blog' example it works fine, so I know that RoR is definitely working in windows!

This is my -'de-identified' config/puma.rb file. Is it because in windows I have no /var/app folder?? I've played around with directories etc to no avail.

`
#!/usr/bin/env puma

# start puma with:
# RAILS_ENV=production bundle exec puma -C ./config/puma.rb

workers 0
theident = 'nameofthing'
application_path =  '/var/app/'+ theident + 'http://.address.com.au/current'
railsenv = 'production'
directory application_path
environment railsenv
daemonize false
pidfile "#{application_path}/tmp/pids/puma-#{railsenv}.pid"
state_path "#{application_path}/tmp/pids/puma-#{railsenv}.state"
stdout_redirect"#{application_path}/log/puma-#{theident}.log"
threads 0, 16
bind "unix:///var/run/puma/" + theident + "_app.sock" `

lundi 25 juillet 2016

Ruby on Rails:Get params with attribute which not in model

I have a field which is not in my model , but it is in my _form.html.erb .Now i want to get it from form, but i get this error :
undefined method 'description' for Object
My controller:
def job_params @job_params ||=params.permit(:description) (description is not an attribute in job model ).
How can i get description ?? My form:

<%= form_for(@job) do |f| %>
<div class="field">
  <%= f.label :description %><br>
  <%= f.text_field :description %>
</div>

Capybara - NameError: uninitialized constant Capybara::TimeoutError

I am creating integration tests for my rails application.

The application I am working to is a little slow. In my test, I execute a certain action within the website (a "saving" - which reloads in the end the page) and the following capybara action runs before the page is actually reloaded.

I cannot use "sleep (seconds)" as this freezes the "reloading" itself.

So I wanted to give a try to this github idea: http://ift.tt/2abMF4v

but I get the following error:

NameError: uninitialized constant Capybara::TimeoutError

Can someone tell me why I get this error and what does it mean?

Rubillow: Error connecting to remote service

I'm working with a rails application. I am using ruby gem rubillow to fetch the US property information. Its working fine on my local but giving error of "Error connecting to remote service". Below is my code:

Rubillow.configure do |configuration| configuration.zwsid = "X1-ZWz1fd7h4ozw23_2hwdv" end property = Rubillow::HomeValuation.search_results({ :address => '2114 Bigelow Ave', :citystatezip => 'Seattle, WA' })

Selenium - WebDriver::Error::WebDriverError: unable to obtain stable firefox connection in 60 seconds

I use Capybara for the integration testing of my application.

After updating my system to the new Ubuntu 16.04, I had to reinstall many of the gems of my application.

Generally the application run successfully, but the integration test has some problem.

Particularly, if a run a test, the browser-simulation does not automatically start anymore and the terminal reports the following:

Warning: Unable to check javascript error status.

Selenium::WebDriver::Error::WebDriverError: unable to obtain stable firefox connection in 60 seconds (127.0.0.1:7055)

Does anyone know how to solve this problem?

How to modify Rails path names dynamically?

My params[:type] equals item (singular)

I need to send the user to

items_path(name: params[:name])

I need to pluralize the params[:type] part of the path and merge it with my view to get my link right, and I'm struggling to do that.

dimanche 24 juillet 2016

How do I test Rails logs in from an Rspec feature spec?

This question tells me how to test logger statements from RSpec model and controller specs. Unfortunately, it doesn't seem to work from a feature spec. With this code:

# controller.rb
def action
  logger.info 'foobar'
end

# spec.rb
scenario 'logging should work' do
  expect(Rails.logger).to receive(:info).with('foobar')
  visit action_path
end

I get the error:

 Failure/Error: visit action_path
   #<ActiveSupport::Logger:0x007ff45b6e5ad0> received :info with unexpected arguments
     expected: ("foobar")
          got: (no args)

The test.log file does not contain foobar, so it seems the test is failing immediately, before the controller action has a chance to complete.

Is there some way to use this expect(Rails.logger) syntax in a feature spec?

Ruby on rails create a new variable to make an each

i'm new into ruby on rails and i want to assign a variable to make an each like this

<% 3.times do |calendar| %>
 <% test = @lessons_calendar %>
   <% test.each do |lesson| %>
     display html here
   <% end %>
<% end %>

The thing is that in my controller i have assigned 3 variables like this @lessons_1 @lessons_2 and @lessons_3 but when i run the code it says undefined method `each' for nil:NilClass, how can i join the number created by calendar to the new variable ? Thanks

Select column from different model and show attributes in view

I have a scaffolded 'Customer.rb' model and a 'Invoice.rb' model. I want people to select a existing Customer from the Customer model and put a few attributes of that selected option in the view of the invoice.

This is the code inside my Invoice#new (@customer = Customer.all in the Invoice_controller)

                <%= @customer.select(:company_name) do |f| %>
                    <h4>Customer:</h4>
                    <div class="well">
                      <address>
                        <strong class="text-dark"><%= f.company_name %></strong><br/>
                        <%= f.first_name + f.last_name if f.first_name.present? && f.last_name.present?%><br/>
                        <%= f.address_line_1 %><br/>
                        <%= f.address_line_2 if present? %>
                      </address>
                    </div>
                <% end %>
              </div>

This shows the correct information but it shows it for ALL columns in the Customers table. I wan't people to pick a specific column only. Like lets say; someone selects 'Coca Cola Ltd.' from a dropdown and then sees only the information of Coca Cola Ltd. (f.company_name: Coca Cola Ltd. etcetera)

The Invoice.rb model contains 'has_one :customer'
The Customer.rb model contains 'belongs_to :invoice'

I tried everything from the ruby on rails guides but i don't seem to get it. Any help would be MUCH appreciated

samedi 23 juillet 2016

How can Iinstall ruby on rails in ubuntu?

I tried to install ruby on rails and I used 'gem install rails', but I got this:

ERROR:  Loading command: install (LoadError)
        cannot load such file -- zlib
ERROR:  While executing gem ... (NoMethodError)
        undefined method `invoke_with_build_args' for nil:NilClass

What am I doing wrong? Or what do I need to do? Can't find help. DO I need to reinstall Ruby? I'm using Ruby2.3 version and ubuntu 16.04. I must say I'm new to ruby on rails, I'm about to learn.

Thanks for your help!

vendredi 22 juillet 2016

Rails 3 joins table and model naming conventions

I am running Ruby 2.1.9 and Rails 3.2.17.

First off, in Rails I always made the assumption that models should almost always be singular. I have seen model names like product_categories_product. This is fine and in habtm situation where you want a model to work with the relationship I have seen instructions_products. Which in Rails sorta may make sense, but I would rather name the model instruction_product. That was associated with a joins table named instructions_products.

In fact I was so frustrated I started looking at how rails names things and this happened? So clearly its an ok name for the model and would correspond to the correct table name. But what is more approriate?

ActiveModel::Naming.singular(InstructionsProducts)

returns instructions_products

Edited: The heart of the question is why is InstructionsProducts a valid model name in rails and why does my example above resolve to the singular 'instructions_products'. This seems odd considering the rails convention is to keep model names singular.

Pluck in a selected object

User.find([1,2,3])

I want to get name only in User model. I don't want to loop in an object so I tried:

User.find([1,2,3]).pluck(:name)

But no luck. How can I do the following scenario using pluck behavior?

jeudi 21 juillet 2016

Rails 3 - Production environment - smtp email issue

I am using smtp settings for sending mails in rails 3. It works fine when sendmail and postfix services are running. But when I stopped those two services then mails stop stop sending and giving me connection error.

Error log -

ERROR -- : (Errno::ECONNREFUSED): Connection refused - Connection refused
org/jruby/ext/socket/RubyTCPSocket.java:126:in `initialize'
org/jruby/RubyIO.java:1178:in `open'

Calling controller method from a helper module

Using Rails 3.2

I'm trying to call expire_fragment, the Rails view method, from a helper but getting an error:

undefined method `expire_fragment' for #<#<Class:0x00000118977110>:0x00000103b853b8>

I'm trying to conditionally clear the cache. This is the helper method call in my view

clear_cache_keys_if(params[:cc], [@product, :search_filters])

And in the helper

  def clear_cache_keys_if(condition, keys = [])
    if condition
      keys.each do |key|
        expire_fragment(key)
      end
    end
  end

I would have thought that the Rails fragment caching methods would be accessible in a helper module, but that doesn't seem to be the case.

I changed it to

controller.expire_fragment(key) 

And that worked.

This method is available in the view. It's available from the controller. I don't really understand why it is not available in a helper. What am I missing here? Why isn't it available in the helper and what is the best way to expose it? Thanks

Retrieve data using for loop in Ruby

I have a question about using foreach loops in ruby. I want to to display documents and I am using a foreach loop in order to display these documents. However, it does give me an error with the "i" variable inside of data["response"]["docs"][i]["topic"] (this is a json string I am iterating over) and I do not understand why that is, can anyone tell me what I am doing wrong? If I simply do data["response"]["docs"][0]["topic"] it works fine but not with the "i" why is that?

<%
(0..10).each do |i|
%>
<%= i %> <br/>
<%= data["response"]["docs"][i]["topic"] %> 
<%
end
%>

Postgres Sequence jumping by 32

We use sequences to maintain the number of orders at a particular business unit. Last few we days, we have noticed that there have been has strange jumps ranging from 1 to 32 in the sequence numbers, multiple times a day. The sequence which we have configured has a cache_value of 1. Why is this happening and how can we resolve this? I couldn't find much documentation regarding the same.

what's the difference between by passing a symbol and string in where clause with joins

I have two models User and Book. User have username and email field, Book have author and title field. When I am using joins to get the users based on associated data with conditions passed in where clause, I am getting different results

  1. When I run this
User.joins(:books).where('author = ? ','xxxx')

Mysql query generated is :

"SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE (author = 'xxxxx' )"

gives me the user whose book include xxxx author whereas

  1. When I run this
User.joins(:books).where(author: 'xxxx')  

Mysql query generated is:

"SELECT `users`.* FROM `users` INNER JOIN `books` ON `books`.`user_id` = `users`.`id` WHERE `users`.`author` = 'xxxx'"

gives Mysql2::Error: Unknown column 'users.author' in 'where clause': SELECT users.* FROM users INNER JOIN books ON books.user_id = users.id WHERE users.author = 'xxxx' ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users.author' in 'where clause': SELECT users.* FROM users INNER JOIN book ON book.user_id = users.id WHERE users.author = 'Dan Brown'

My question : is when I am passing a string encapsulated field and value in where clause it gives me result but when I pass a symbol in where clause it gives me mysql unknown column error. So how does ruby interpreter know from where to fetch data in symbol passing and string passing

mercredi 20 juillet 2016

Running rake test on a Rails app that uses minitest only runs a single test. Is ruby deprecation a cause?

I'm currently trying to run tests in a Ruby on Rails app hosted with Puma instead of WeBrick. This is on Windows. Below is the error I get.

C:\Users\Ka\Desktop\code\developmentdatabase>bundle exec rake test
    ansi: 'gem install win32console' to use color on Windows
    RubyDep: WARNING: Your Ruby is outdated/buggy. (To disable warnings, set RUBY_DEP_GEM_SILENCE_WARNINGS=1)
    RubyDep: WARNING: Your Ruby is: 2.2.4 (buggy). Recommendation: install 2.2.5 or 2.3.1.
    Started with run options "-n=/^(EditTest\\#test_requires_a_log_message)$/" --seed 3480

      0/0: [===================================] 100% Time: 00:00:00, Time: 00:00:00
     FAIL["test_requires_a_log_message", EditTest, 0.7240425939962734]
     test_requires_a_log_message#EditTest (0.72s)
            Expected true to be nil or false
            test/models/edit_test.rb:45:in `block in <class:EditTest>'

      0/0: [===================================] 100% Time: 00:00:00, Time: 00:00:00
    WARNING: Your progress bar is currently at 0 out of 0 and cannot be incremented. In v2.0.0 this will become a ProgressBar::InvalidProgressError.
      0/0: [===================================] 100% Time: 00:00:00, Time: 00:00:00

    Finished in 0.72932s
    1 tests, 1 assertions, 1 failures, 0 errors, 0 skips
    20:01:43 - INFO - Run 'gem install win32console' to use color on Windows

I am unable to make my Rails app use the ruby 2.3.1, which I detail extensively in this thread which is still unanswered. But the gist is that ruby -v shows 2.3.1, but Rails won't use it.

Here's the Gemfile for the test environment:

group :test do
  gem 'minitest-rails'     # Test library
  gem 'minitest-rails-capybara' # Integration tests
  gem 'minitest-reporters' # For progress bar, etc.
  gem 'minitest-fail-fast' # End testing on first failure
  gem 'minitest-focus'     # One test at a time
  gem 'codeclimate-test-reporter', require: nil
  gem 'launchy'
  gem 'rake' # Specified for Travis CI
  gem 'webmock' # Disable network connections
end  

Uniqueness with has_many on Rails migration (without through)

I am creating a Rails migration for provinces and countries. The idea is that for each country, we can't allow more than one province with the same name.
My create_provinces migration is:

class CreateProvinces < ActiveRecord::Migration
def change
    create_table :provinces do |t|
      t.string :name
      t.references :country, index: true, foreign_key: true
    end
end


My country.rb is:

class Country < ActiveRecord::Base
  has_many :provinces, :uniq => true
end

My province.rb is:

class Province < ActiveRecord::Base
  belongs_to :country
  private
  validates_presence_of :country
  validate :canada_or_usa?
  validates_presence_of :name
  validate :in_right_country?
  validates_associated :country
  def canada_or_usa?
    errors.add(:country, "can only add province for Canada or the United States") unless (country.name == "Canada" || country.name == "United States")
  end
  def in_right_country?
    if country.name == "Canada"
      errors.add(:name, "Name must be the name of a province in Canada") unless (DataHelper::canada_provinces_with_caption.include? name)
    end
    if country.name == "United States"
      errors.add(:name, "Name must be the name of a province in the United States") unless (DataHelper::usa_provinces_with_caption.include? name)
    end
  end
end

With :uniq => true in country.rb, I am getting the error that says :uniq is not a known key. Note that I also am not using through as per other questions. Is there a way to make sure each country can't have two provinces with the same name?

Refinery CMS: Uncaught TypeError: undefined is not a function - init_sortable_menu

I'm using gem 'refinerycms', '~> 2.0.0' ruby '2.2.3' and gem 'rails', '3.2.22'

But when i edit any page then i'm facing following issue. Can someone guide me what will be the issue?

Uncaught TypeError:

undefined is not a function

init_sortable_menu init_refinery_admin jQuery.Callbacks.fire

jQuery.Callbacks.self.fireWith refinery.js:436

jQuery.extend.readyrefinery.js:950 DOMContentLoaded

ActiveRecord::AssociationTypeMismatch gotNilClass

I am a beginner programmer in Ruby and Ruby on Rails , I'm trying to run a rake command in my task , but when I do the following happens:

rake daily_tasks:process_api

rake aborted! ActiveRecord::AssociationTypeMismatch: State(#47392639701120) expected, got NilClass(#47392580444120) /home/thiagoamaralr/Desktop/proponente-master-74f8a3b2ddb02a90b2c173cf31383505018d02dd/app/services/create_programa_api.rb:21:in call' /home/thiagoamaralr/Desktop/proponente-master-74f8a3b2ddb02a90b2c173cf31383505018d02dd/lib/tasks/daily_tasks.rake:7:inblock (3 levels) in ' /home/thiagoamaralr/Desktop/proponente-master-74f8a3b2ddb02a90b2c173cf31383505018d02dd/lib/tasks/daily_tasks.rake:5:in each' /home/thiagoamaralr/Desktop/proponente-master-74f8a3b2ddb02a90b2c173cf31383505018d02dd/lib/tasks/daily_tasks.rake:5:inblock (2 levels) in ' Tasks: TOP => daily_tasks:process_api (See full trace by running task with --trace)

Follow the task I'm trying to run:

namespace :daily_tasks do

desc "Process the day to day tasks" task process_api: :environment do

SiconvApi::Programa.find.each do |programa|
  if programa.data_inicio_recebimento_propostas && (programa.data_inicio_recebimento_propostas.to_date >= Date.parse("2015/06/01"))
    CreateProgramaApi.call(SiconvApi::Serializers::Programa.new(programa))
  end
end

Thank you in advance for your attention!

Using secret passwords in Rails App

I am working on a rails application where I need to send an issue on github if a certain process takes place. Now, to send a post request I need to use my github username and password. Obviously, I can't use my password in open so what should I do?

I know something about secrets.yml file in rails config but I can't even put my password there. I will put my app on github and anyone can hence access. How should I use secrets.yml file to store my password and use it in my rails app?

How to prevent writing 'object' field in PaperTrail

  1. I have many fields in my table, I don't want to version all columns. How do I skip the columns which I don't need to store any changes

I have used the following, but it stores the values in 'versions' table. In my model

class User < ActiveRecord::Base
  has_paper_trail skip: [:foo1, :foo2, :foo3]
  # tried with ignore instead of skip
end

  1. How do I prevent writing object field in 'versions' table.

Call dependencies using string formatted object

Is there a way to call dependencies in a string format?

Here are my models:

User

has_many :addresses

Address

belongs_to :user

And here is I am trying to do. I want do get all addresses of specific user and I want "addresses" to be a string because I want to make it dynamic. For example, I want to change "some_models_related_to_user".

user."addresses".first

Thanks!

A General Method which can be called before Every Available rakes

My aim is that,in my rails project there are around 40 rakes present.What client need before starting each rake, create an entry in a table with the rake name, arguements, start time and end time. Also i dont want to update existing rake files for that, is it possible to do that outside the rakefiles. I have tried updating in the rakefile. But it is no use.TIA.

mardi 19 juillet 2016

Rails, Query polymorphic association

I'm trying to querying on polymorphic associations in Rail, and come across with this problem. I have a few models, User, MorningVisit, AfternoonVisit, NightVisit, and Result

class User < ActiveRecord::Base
    attr_accessible :name
    has_one :morning_visit
    has_one :afternoon_visit
    has_one :night_visit
end

class MorningVisit < ActiveRecord::Base
    belongs_to :user
    has_many :results, as: :visitable
end

class AfternoonVisit < ActiveRecord::Base
    belongs_to :user
    has_many :results, as: :visitable
end

class NightVisit < ActiveRecord::Base
    belongs_to :user
    has_many :results, as: :visitable
end

class Result < ActiveRecord::Base
    belongs_to :visitable, polymorphic: true
end

Everything stores perfectly, but now I need to do some search and querying on User using filterrific.

If I do

includes(:visitable => :user).order("user.name")

I get

Can not eagerly load the polymorphic association :visitable

So I tried to manually joined MorningVisit with

.joins( "JOIN morning_visits ON lab_results.visitable_id = morning_visit.id AND lab_results.visitable_type = 'MorningVisit'")
.joins( "INNER JOIN `users` ON `morning_visits`.`user_id` = `users`.`id` ")

And order("user.name") works.

But if I added

.joins( "JOIN afternoon_visits ON lab_results.visitable_id = afternoon_visits.id AND lab_results.visitable_type = 'AfternoonVisit'")

It returns nothing. And if I tried outer join, it keep telling me my SQL syntax was wrong.

Does anyone have a solution for this?

Can we use multiple tables(created on fly) for a single model in rails?

I have a model TempUser that is used for data crunching using lots of queries to narrow down the result. Its a replica of User Model. For narrowing down the result it copies the all the records from users_table into temp_users_table and keeps deleting record according to filters applied on it so that in the end I only have filtered users in TempUser model where I can perform more active record operations on the residual data.

I am trying to make dynamic tables for TempUser Model so that If more than one user request for TempUser Model then he should have different temp_user_dynamic_table to perform operations on it. Is it possible?

something like:-

class TempUser < ActiveRecord::Base
end

which has multiple dynamic tables created on fly when new request comes in like:- temp_users_table1,temp_users_table2

Rails won't use my version of Ruby on my environment [Windows, using uru not rvm]

I have the latest version of Rails and Ruby from RailsInstallers. I need to update Ruby to ruby 2.3.1. I use uru as an alternative for rvm. I successfully use uru to point to ruby 2.3.1. When I do ruby -v, it shows ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32].

Fantastic.

However, when I do rails s, it tells me Your Ruby version is 2.2.4, but your Gemfile specified 2.3.1. Please help me. I've gone through every thread before posting.

Here's what I've tried:

  1. Delete the Ruby folder from RailsInstaller directory. => rails s is not recognized as an internal or external command, operable program or batch file.
  2. Delete and replace the old Ruby with the new Ruby directory => same thing

Contemplating that this is a RailsInstaller error.

How long should a Microsoft Azure machine learning API take to respond?

I've been trying to use a web app made in Ruby on Rails to access Microsoft's machine learning API. I already designed the API and deployed it as a web service, but all calls I have made so far have timed out and exceeded Heroku's 30 second limit. Is this a sign that something in my implementation is wrong, or is it normal to take that long and I should go for an asynchronous approach using Blobs instead?

Here is my sample HTTP post code:

def post
    url = @api_url
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    @request = Net::HTTP::Post.new(@api_url)
    @request.set_form_data({"Authorization" => "Bearer #{@api_key}", "Content-Length" => "#{@payload.length}", "Content-Type" => "application/json", "Accept" => "application/json"})
    @request.body = @payload
    resp = http.request(@request)
end

Cloudinary download_archive_url returns a url with spaces

I have been using the Cloudinary Uploader API method create_archive to gather a bunch of file names (public_ids) and create/upload an archive to my cloudinary account. Then I was able to parse through the response and get a succinct secure url to that archive which I could mail to the user. But then we decided we wanted to incorporate a 24 hour expiry timestamp on our archives. I found in the API documentation that you can use a parameter called expires_at if you are using the download API methods instead of the create API methods.

The difference is rather than calling Cloudinary::Uploader.create_archive(options = {}) I would have to call Cloudinary::Utils.download_archive_url(options = {}) which instead of returning a hash object would return a big chunky generated url listing all of the public_ids in the url.

I was able to confirm that the expires_at parameter was being set but when I get the url back from Cloudinary it has a bunch of spaces in it. I found a direct correlation between the length of the generated url and these disruptive spaces showing up in the url.

I tried gsub'ing out the spaces using /\s+/, "%20", and " ", none of which work.

Has anyone else experienced this anomaly? If so how did you overcome it?

master failed to start

Facing an Issue

Deploying a Rails 5 App with Capistrano. Deployment Fails while trying to start Unicorn with thus error message

 master failed to start, check stderr log for details

The Same Error, if i start Unicorn with this command

bundle exec unicorn -D -c /home/deploy/apps/app_production/shared/config/unicorn.rb -E production

Details of unicorn.log

bundler: failed to load command: unicorn      (/home/deploy/apps/app_production/shared/bundle/ruby/2.3.0/bin/uni  corn)
LoadError: No such file to load -- zip ...

Installed Ruby(2.3.1p112) User wide with rbenv.

Any help in resolving this would be appreciated.

Thank You

ruby on rails when making new app it says unknown encoding name . on windows 7, rails 4.2

when I type "rails new ..." it goes well until it reaches:

run bundle install

C:/RailsInstaller/Ruby2.2.0/lib/ruby/2.2.0/win32/registry.rb:71:in `find':unknown encoding name - CP720 (ArgumentError)

I have already changed the encoding name by " chcp 1252 " which I found in another answer rails4 unknown encoding name - CP720 , because it was giving me " unknown encoding name - CP720 (ArgumentError) " when I was trying to know the version of the rails through " rails -v "

If anyone knows how to solve this please tell me , and if you need more information tell me what you need to know and I will type it in a comment .

Thank you very much .

RoR: The right way of rescuing a DB exception on save?

I've recently faced the problem of my DB failing with Adaptive Server connection timed out quite often after I try to save an ActiveRecord model.

If I try to rescue this failed attempt I get ActiveRecord::StaleObjectError, so I have to recreate the object being saved from the very beginning which may be quite an expensive procedure.

What is the right way of handling this situation on the app side given that I cannot affect DB performance in any way?

Using Ruby on Rails, How can I put data in a new table line?

I'm a beginner in Ruby on Rails. And I'm korean. So my words are little weired... My question is this... If I have 10 data, I want to put 1~5th data in a first line and 6~10th data in a second line.

like this

I've try this codes

              <table border height=300 width=300 align=center>
                <thead>
                  <tr style="font size:20;">
                    <th></th>
                    <th></th>
                  </tr>
                </thead>

                <tbody>
                  <% if current_user.samulham.nil? %>
                    <tr>
                      <% @samulham.each do |x| %>
                         <% if x.user_id.present?%>
                           <td><%= "X" %></td>
                         <% else %>
                           <td><%= link_to "#{x.lockernumber}", {:controller => "home", :action => "register", :cur_user => current_user.id, :cur_samulham => x.id}, method: :post %></td>
                         <% end %>
                      <% end %>
                    </tr>
                  <% end %>
                </tbody>
              </table>

Thank you for your considering. :)

Does rename_column in Rails ActiveRecord Migration preserve the old column data type?

I am trying to run a rails migration where in I am changing just the column name. So, this rails takes care of keeping the same data type as the old column or tries to make a guess based on the column content?

def change
   rename_column :marks, :percent, :percentage
end

The old type was decimal and after migration it still remains decimal. Just I wanted to know the type was preserved because the existing values were decimal or it was because of the old data type.

lundi 18 juillet 2016

CSV not working with carrierwave downloaded file object

I am uploading file with csv format over rack using carrierwave in my rails controller.

Once upload, I use url(cdn) in my worker for download that file from rack and use it in my worker using following line:

file = CarrierWave::Uploader::Download::RemoteFile.new(<url(cdn)>)

Now I am having object of carrierwave which is having reference of CSV file which is uploaded to rack something like below:

#<CarrierWave::Uploader::Download::RemoteFile:0x007ffac0ab5050 @uri="<URL of rack>">

I am using this file object with methods with CSV class like below:

CSV.foreach(file, headers: false) do |row|
  puts row
end

I am getting following error:

*** TypeError Exception: no implicit conversion of CarrierWave::Uploader::Download::RemoteFile into String

nil

Any help would be appreciated!

Can I reuse my integration test suite to profile a Rails app?

Most posts on Rails profiling recommend Ruby-Prof. To use Ruby-Prof I need to write at least one new test for each controller action, then manually compare the results to see what's taking the longest and might be a candidate for optimization.

This is good if I already know exactly what request I'm focusing on. It seems less good if I'm trying to identify the hot spots in the first place. Given that I already have a huge integration test suite covering all the app's functionality that I care about, it seems like what I really want to do is:

  1. Run the entire test suite and capture the time spent in each controller action. (Or model method, or whatever level of granularity I want.)
  2. Print two lists, of worst-case and average-case times in each controller action.
  3. Sort each list and start investigating the longest-running controller actions, now using Ruby-prof or other profiling tools to drill down into the call stack. The worst-case times will identify request params that might be problematic (i.e., trigger slow code on the backend), without my having to think of them all when I write the performance test.

Is there some reason people don't use the integration test suite in this way, rather than basically duplicating it with a second performance test suite? I have not seen it suggested. Before I write code to do something like this (presumably with a before_action in ApplicationController, is there already a tool for this?

Setting the expires_at parameter on a download_archive_url doesn't seem to do anything

I'm trying to override the default expiration timestamp on a download_archive_url when creating an archive using the Cloudinary::Utils.download_archive_url(options = {}) call. I see in the documentation the expires_at parameter is described as follows:

The date (UNIX time in seconds) for the URL expiration (e.g., 1415060076). Only relevant when using the 'download' SDK methods and the 'download' mode in direct calls. Default: 1 hour from the current time.

I set the mode to download in my options and included :expires_at => (Time.now + 24.hours).to_i in the options, but when I run the download command and generate the download url to pass along to my Mailer there isn't an expires_at parameter present in the url.

Has anyone had success setting the expires_at parameter in either the Cloudinary::Utils.download_archive_url or the Cloudinary::Uploader.create_archive API calls?

Improving this mix in

I’m trying to improve this mixin and the one thing that’s bothering me is I can’t seem got get the rest of the module to know about the base property in the self.included(base) so I’m having to pass base to every module method. Is there a better way of doing this:

module SearchSort
      def self.included(base)
        # binds included class's class methods
        base.send :extend, ClassMethods
        initialize_scopes(base)
      end

      def self.initialize_scopes(base)
        initialize_type_scope(base)
        initialize_product_name_scope(base)
      end

      def self.initialize_type_scope(base)
        base.scope :for_work_type, lambda { |work_type|
        Rails.logger.debug("-----(45) work_type #{work_type}")
        terms = process_terms(work_type)
      base.where(
        terms.map { '(LOWER(workable_type) LIKE ?)' }.join(' AND '),
        *terms.map { |e| [e] * 1 }.flatten)
    }
  end

  def self.initialize_product_name_scope(base)
    base.scope :for_product_name, lambda { |product_name|
      terms = process_terms(product_name)
      base.where(
        terms.map { '(LOWER(products.name) LIKE ?)' }.join(' AND '),
        *terms.map { |e| [e] * 1 }.flatten
      ).joins(:product)
    }
  end

  module ClassMethods
    def pid_opts
      [%w(Newly\ Added newly_added), %w(Waiting waiting),
       %w(Ready ready), %w(Working working),
       %w(Error error), %w('Error Retry', 'error_retry'),
       %w(Done done), %w(Gated gated)
      ]
    end
  end
end

Rails Query to return users belongs to any cities & not belong to any cities

I have Many to Many associations between two tables For Ex users & cities

users
id  name
1   Bob
2   Jon
3   Tom
4   Gary
5   Hary

cities
id     name 
1      London
2      New-york
3      Delhi

users_cities
id   user_id   city_id
1    1         2
2    2         1
3    3         1
4    3         2

I want two sql queirs

Query which accepts array of city_id and return all the users belongs to that cities. For Ex when city_id : [1, 2] then result should be O/P should be

   id  name
        1   Bob
        2   Jon
        3   Tom

Query which accepts array of city_id and return all the users which are not belongs to that cities. For Ex when city_id : [1, 2] then result should be O/P should be

    id  name
    4   Gary
    5   Hary

Note:- i am using

user.rb

has_and_belongs_to_many :cities

city.rb

has_and_belongs_to_many :users

Rails Paper Trails delete existing versions with the condition

I want to delete the old entries of an entity in the 'versions' table with the following conditions

  1. First, It should be sorted by the recently modified

  2. I would like to remove all records which have more than 10 entries for an entity (i.e. a single row)

Is there a query which I can use to delete this.

My current proposal to remove such versions is as follows:-

entities.each do |entity|
   versions = entity.versions.order('created_at DESC')
   if versions.count > 10
     #deleting all remaining versions except the 10 entries
   end
end

dimanche 17 juillet 2016

Phusion Passenger Enterprise 5.0.29 will not load rails 3.2 application

I have run Phusion Passenger Enterprise as a customer for several years. I have it running an old Rails 2.3 application that is being re-written. I purchased another license to run a Rails 3.2 application that is next in line.

Unfortunately, it won't run the 3.2 application. The 2.3 app runs flawlessly, but there's nothing I can do to figure out this error. In the past I have had questions answered on SO from the support staff but that may not be the case anymore. I feel like this is something simple.

An error occurred while starting up the preloader. It sent an unknown response 
type "socket: http://unix:/tmp/passenger.PvoMBu8/apps.s/preloader.qd7yzy\n".

This is running on RHEL 6. The installed PCRE module is not recognized, and the software was unable to automatically install it due to an inability to get the checksum, but I feel like that might be a separate issue.

Rails simple_form with multi belongs_to association

In my app I have lots of model: (products belongs_to creator, creators belongs_to compagnie, compagnies belongs_to SEO, SEOs belongs_to user)

in my first Seoscontroller I have that:

def create
 @seo = current_user.seos.build(seo_params)
   if @seo.save
    redirect_to search_path
   else
    render :new
   end
end

(Controller work find!)

In the Compagniescontroller I think (but not work:[ )

def create
  seo = Seo.find(params[:seo_id])
   @compagnie = seo.compagnies.build(compagnie_params)
  if @compagnie.save
   redirect_to search_path
  else
   render :new
  end
end

and in my simple_form....

<%= simple_form_for @compagnie(seo_id: seo.id) do |f| %>
<% end %>

I search a solution for associate my model id to the controller and the simple_form_for

  create_table "seos", force: :cascade do |t|
   t.string   "name"
   t.string   "surname"
   t.datetime "created_at", null: false
   t.datetime "updated_at", null: false
   t.integer  "user_id"
   t.index ["user_id"], name: "index_seos_on_user_id", using: :btree
  end

  create_table "compagnies", force: :cascade do |t|
    t.string   "compagnie_name"
    t.string   "address"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.integer  "seo_id"
    t.integer  "user_id"
    t.index ["seo_id"], name: "index_compagnies_on_seo_id", using: :btree
    t.index ["user_id"], name: "index_compagnies_on_user_id", using: :btree
  end

User model

class User < ApplicationRecord

  has_many  :seos
  has_many  :compagnies
end

Seo model

class Seo < ApplicationRecord

    belongs_to  :user
    has_many    :compagnies

    validates :name,        presence: true
    validates :surname,      presence: true
end

compagnie model

class Compagnie < ApplicationRecord

     belongs_to :user
     belongs_to :seo


    validates :address,                 presence: true
    validates :compagnie_name,          presence: true
end

form for Seo

            <%= simple_form_for @seo do |f| %>
        <div class="search__form--left split-panel--left">
            <div class="search__title">
                Seo:
            </div>


                <div class="search__section search__section--od">

                    <!--Name-->
                    <div class="search__field search__departure grouped-input--top">
                        <%= f.input :name, placeholder: "name", :input_html => { :class => "add__name-input ember-text-field textfield station-text-field empty station-text-field-- add__input empty" }, label: false %>
                    </div>

                    <!--Surname-->
                    <div class="search__field search__arrival grouped-input--bottom">
                        <%= f.input :surname, placeholder: "prenom", :input_html => { :class => "add__name-input ember-text-field textfield station-text-field empty station-text-field-- search__input empty" }, label: false %>
                    </div>
                </div>

                <!--Button-->
                <div class="search__button progress-button">
                    <%= f.button :submit, "Add", class: "button progress-button--button" %>
                </div> 

        </div>
    <% end %>

form for compagnie

    <%= simple_form_for @compagnie(seo_id: seo.id) do |f| %>
        <div class="search__form--left split-panel--left">
            <div class="search__title">
                Seo:
            </div>


                <div class="search__section search__section--od">

                    <!--Name-->
                    <div class="search__field search__departure grouped-input--top">
                        <%= f.input :address, placeholder: "address", :input_html => { :class => "add__name-input ember-text-field textfield station-text-field empty station-text-field-- add__input empty" }, label: false %>
                    </div>

                    <!--Surname-->
                    <div class="search__field search__arrival grouped-input--bottom">
                        <%= f.input :compagnie_name, placeholder: "compagnie_name", :input_html => { :class => "add__name-input ember-text-field textfield station-text-field empty station-text-field-- search__input empty" }, label: false %>
                    </div>
                </div>

                <!--Button-->
                <div class="search__button progress-button">
                    <%= f.button :submit, "Add", class: "button progress-button--button" %>
                </div> 

        </div>
    <% end %>

Thanks

samedi 16 juillet 2016

how to sending mail from an account in rails application with out given Password Credential?

I am implementing one of my client requirement..i.e., sending mail from an account in application with out given Password Credential i am also surprised after saw this method one of the website i.e.,

        http://ift.tt/28W51b7 

i am sending mail through this web ...but all sending mail updated in my gmail sent item... i have trying in this way by setting up in config file

     config.action_mailer.perform_deliveries = true

    config.action_mailer.default_url_options = { host: 'localhost', port: 9292}
      config.action_mailer.delivery_method = :smtp
      ActionMailer::Base.smtp_settings = {
      address:        'imap.gmail.com'or'imap.hotmail.com'or'imap.yahoo.com', # default: localhost
     port:           '993',                  # default: 25
     user_name:      'debasish.industrify2016@gmail.com',
        password:       'deb@industrify',
       authentication: :plain                 # :plain, :login or :cram_md5
      }

How to render a google drive file in to rails app

I have some html files stored in Google drive, I wanted those files to render in to my new rails app, is there any possibility to render a view of the Google drive file in to rails app ?

Please help me. Thanks.

vendredi 15 juillet 2016

Rails 3 joins table and model naming conventions

I am running Ruby 2.1.9 and Rails 3.2.17.

First off, in Rails I always made the assumption that models should almost always be singular. I have seen model names like product_categories_product. This is fine and in habtm situation where you want a model to work with the relationship I have seen instructions_products. Which in Rails sorta may make sense, but I would rather name the model instruction_product. That was associated with a joins table named instructions_products.

In fact I was so frustrated I started looking at how rails names things and this happened? So clearly its an ok name for the model and would correspond to the correct table name. But what is more approriate?

ActiveModel::Naming.singular(InstructionsProducts)

returns instructions_products

This is a working model name in rails. What gives?

How to export data to a specific cell in excel using rails 3

My rails 3 project has an excel file with shipping template in it. Now, i need to put some info into this excel sheet and into a specific cells up on a button click. Can someone please tell me how to do this or is there any material available online.

Comma and Dot concurrently on rails in numeric fields

somebody know a trick for use Comma and Dot concurrently in a decimal field, because the international separator is the Dot but in some country is the Comma. i've try with a Before_validation, but i've a lot of problem, sometimes works sometimes doesn't, this is the code:

def update_fields
    [:field_1, :field_2, :field_3].each { |k|
      unless k != nil
        self[k.to_sym] = self.attributes_before_type_cast[k.to_s].gsub(/[.,]/, '.' => '', ',' => '.')
      end
    }
end

thanks in advice.

Missing template layouts/mailer with {:locale=>[:en], :formats=>[:html],

I'm following michael harlt rails tutorial but i get this error

Missing template layouts/mailer with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in: * "/home/ubuntu/workspace/app/views"

when previewing account activation

This is my user_mailer.rb

class UserMailer < ApplicationMailer

  def account_activation(user)
    @user = user
    mail to: user.email,  subject: "Account activation"
  end

  def password_reset
    @greeting = "Hi"

    mail to: "to@example.org"
  end
end

and the error highlights the line that says

mail to: user.email,  subject: "Account activation"

I tried adding layout 'mailer' in user_mailer.rb but it doesn't work.

Limit association based on rich relation attributes

first question for me here! Im trying to assign 'key companies' to my users. These are found in a many-to-many rich join table. On this table there are attributes like new, key, active and so forth. I want to assign companies to users in a long list and for that Im using SimpleForm.

Everything is working excepts that I want to filter out and limit the association relation based on the attributes on the rich relation. I have company relations for each user but not all of them are akey-relation or a new-relation for example. I only want the association being key to show up and not touch the other ones. I also want to set the attribute active to true when Im assigning these companies to the users. My code looks like this now:

user.rb

class User < ActiveRecord::Base
    has_many :company_user_relationships
    has_many :companies, through: :company_user_relationships

company.rb

class Company < ActiveRecord::Base
    has_many :company_user_relationships
    has_many :users, through: :company_user_relationships

schema.rb

create_table "company_user_relationships", force: true do |t|
  t.integer  "company_id"
  t.integer  "user_id"
  t.boolean  "key"
  t.boolean  "active"
  t.datetime "last_contacted"
  t.string   "status_comment"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "status"
  t.boolean  "new"
end

users_controller.rb

def assign_key_companies
    User.update(params[:users].keys, params[:users].values)
    redirect_to(:back)
end

view

= form_for :user_companies,
        url: assign_key_companies_users_path,
        html: {:method => :put} do |f|
  - users.each do |user|
    = simple_fields_for "users[]", user do |u|
      tr
        td.col-md-4
          = "#{user.first_name} #{user.last_name}"
        td.col-md-8
          = u.association :companies, label: false, collection: @key_company_candidates,
                      input_html: {data: {placeholder: " Assign key companies"}, class: 'chosen-select'}
  = submit_tag "Save key companies", class: "btn btn-success pull-right"

I basically want to only show user.companies.where(key: true) and the SQLCOMMIT to always put the key-field to true when updating the record.

How can i filter out to only affect the associations I want?

Mail not sending from ewebguru domain Rails

I have a domain techo.com (bought from ewebguru) and I'm tryng to send mail from my rails app but mail is not sending I'm using following code configuration in production and development :

{
  :user => 'abcd@techo.com',
  :password => '*********',
  :domain => 'techo.com',
  :port => 25,
  :authentication => :none 
}

somebody suggest me to do these :

User: mail id
Password: mail id password
SMTP Server: tecorb.com
SMTP Port: 25
POP Port: 110
SSL Authentication:None

I'm not getting how to configure these into my development.

Please suggest me.

jeudi 14 juillet 2016

Resque mailer undefined method for Hash on production

i'm trying to setup resque mailer on production but on Queues still failing and showing this undefined method for Hash.

Please someone have a idea how to fix it?

undefined method `email' for #<Hash:0x007fcfaeb88280>

my mailer confing

config.action_mailer.default_url_options = { host: 'localhost' }

  ActionMailer::Base.smtp_settings = {
    address: 'smtp.gmail.com',
    port: '587',
    domain: 'xxxx.com',
    authentication: :plain,
    user_name: 'xxxx@gmail.com',
    password: 'xxxx',
    enable_starttls_auto: true
  }
end

resque initializer
require "resque/tasks"

task "resque:setup" => :environment

mailer

class UserMailer < ActionMailer::Base
  default from: 'xxx'
  include Resque::Mailer


  def registration_confirmation(user)
    @user = user
    mail to: user.email, subject: 'Confirm registration', &:html
  end

using a generic error handler after `render` has been called

I'm working on a Rails 3 API project and am running into an AbstractController::DoubleRenderError, which I would like to avoid.

There is a filter that is executing on both sides of a controller action that is raising an unexpected exception after the controller action has completed. Because the controller action has completed, render has already been called. A rescue_from handler that is configured in the controller base class then kicks in and attempts to render a generic JSON error message, but since the controller action has already called render the AbstractController::DoubleRenderError is raised.

Is there a way in Rails 3 to avoid assuming that a controller action render is the last nontrivial user code that will be executed so that errors can be gracefully handled after any action render calls?

login with devise with 2 params in one field Rails

i want to login with a dynamic field like i did it here:

<%= form_tag(dynamic_login_path, method: "post", id: "login_cellphone_email") do %>

        <div class="form-group">
            <%= text_field :cellphone_email, "", :class => 'form-control', :id => 'email-phone-login', :placeholder => 'Enter a email or cellphone' %>
        </div>

        <div class="form-group">
            <%= password_field :password, "", :class => 'form-control', :id => 'password-login', :placeholder => 'Enter your password' %>
        </div>

        <%= submit_tag 'Check', :class => 'btn btn-default btn-block' %>
 <% end %>

here i make a form with a field that can be the email or cellphone then in the controller i check if its a email or cellphone and if its i check for the user who has this email/cellphone and this password but i want to use devise now for the sessions but i dont know if i can do this on it, i can?

how to stop the install the sqlite3 adapter: `gem install activerecord-sqlite3-adapter` on the server

I'm deploying a app on production mode but when i try to finish the process the aways show this need for sqlite adapter, please someone know how to stop this issue?

i've been using RAILS_ENV=production but in this case did not worked.

current$ rails generate admin_interface:setup RAILS_ENV=production
DEPRECATION WARNING: Support for Rails < 4.1.0 will be dropped. (called from warn at /home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/2.2.0/forwardable.rb:183)
/home/ubuntu/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bundler-1.12.5/lib/bundler/rubygems_integration.rb:322:in `block in replace_gem': Please install the sqlite3 adapter: `gem install activerecord-sqlite3-adapter` (sqlite3 is not part of the bundle. Add it to Gemfile.) (LoadError)
    from /home/ubuntu/vitrineonline/releases/10/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/sqlite3_adapter.rb:3:in `<top (required)>'
    from /home/ubuntu/vitrineonline/releases/10/vendor/bundle/ruby/2.2.0/gems/backports-3.6.8/lib/backports/std_lib.rb:9:in `require'
    from /home/ubuntu/vitrineonline/releases/10/vendor/bundle/ruby/2.2.0/gems/backports-3.6.8/lib/backports/std_lib.rb:9:in `require_with_backports'
    from /home/ubuntu/vitrineonline/releases/10/vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `block in require'
    from /home/ubuntu/vitrineonline/releases/10/vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /home/ubuntu/vitrineonline/releases/10/vendor/bundle/ruby/2.2.0/gems/activesupport-3.2.22/lib/active_support/dependencies.rb:251:in `require'
    from /home/ubuntu/vitrineonline/releases/10/vendor/bundle/ruby/2.2.0/gems/activerecord-3.2.22/lib/active_record/connection_adapters/abstract/connection_specification.rb:50:in `resolve_hash_connection'

How to test if a child record got created in Rails controller test?

I have the following controller test which tests if the user got created successfully. But I am not sure how to test if the child record (role) got created successfully or not.

Please guide.

users_controller_test.rb

    class UsersControllerTest < ActionController::TestCase
     test "should create user" do
        assert_difference('User.count') do
          post :create, user: { first_name: 'Controller User First Name', last_name:"Controller User Last Name", email: 'fisrtlast@email.com',
                                phone: '1111111111', time_zone: 'Eastern Time (US & Canada)', password: 'Password123',
                                password_confirmation: 'Password123', client_ids: '339762980', store_ids:['','248505843',''],
                                profile_id: '417269330'}, commit: 'Create User'
        end

        assert_redirected_to user_path(assigns(:user))
      end
   end

users_controller.rb

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)
    @user.locale = I18n.default_locale

    respond_to do |format|
      if @user.save
        @user.roles.concat(@user.profile.roles)
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

user.rb

class User < ActiveRecord::Base
  has_many :stores, through: :store_user_assignments
  belongs_to :profile
end

create node attribute/return value in custom resource for chef

I have a chef resource that needs to return a version. I looked up and fund the best way to publish it as a node attribute. Here is the resource code(dj_artifactory_version) :

require "open-uri"
require "json"


def whyrun_supported?
  true
end

def get_version(name, user, pass, type, organization, art_module, repos, version)
  if (type.match(/snapshot$/i) and version.match(/latest$/i))
     string_object = open("http://ift.tt/29GeDC5}", :http_basic_authentication=>["#{user}", "#{pass}"], :ssl_verify_mode=>OpenSSL::SSL::VERIFY_NONE)
     json_file = JSON.parse(string_object.read)
     version_array = Array.new
     json_file["results"].each do |version|
       version_array.push(version["version"])
     end
     unique_versions=(version_array.uniq).max
     node.set['artifact']['snapshot']['latest'] = unique_versions

Now I use this chef resource in my recipe to get the version :

dj_artifactory_version "test" do
  type "snapshot" # options - snapshot/release
  organization "djcm.billing.api.admin" # layout.organization in artifactory properties.
  modules "paypal" # layout.properties in artifactory properties.
  repos  "djcm-zip-local" # repository name in artifactory
  version "latest" #latest/oldest
end

p "#node{['artifact']['snapshot']['latest']}"

I create default['artifact']['snapshot']['latest'] in default.rb with a value but here even after I run my recipe the old value doesn't change. Interestingly when I print the same in my resource, it print the node with the new value.

What am I doing wrong and is there a better way to publish a value using your own resource ?

action mailer error to deliver email

I am trying implementing send mail through action mailer in rails related code are..

my mailers/user_mailer.rb

          class UserMailer < ActionMailer::Base
    default :from => "bkdebasish90@gamil.com"
     def registration_confirmation(user)
        mail(:to=>user.email, :subject =>"Registered")
        end
        end

users.controller is

  def create
     @user = User.new(user_params)
        respond_to do |format| 
    if @user.save
    UserMailer.registration_confirmation(@user).deliver
      format.html { redirect_to @user, notice: 'User was successfully   created.' }
       format.json { render :show, status: :created, location: @user }
      else
     format.html { render :new }
    format.json { render json: @user.errors, status: :unprocessable_entity }
   end
   end
  end  

Here, Your initializer\setup_mail.rb setting will go to the development.rb

    config.action_mailer.default_url_options = { host: 'localhost', port: 9292 }

    config.action_mailer.delivery_method = :smtp
      config.action_mailer.smtp_settings = {
        :address     =>"smtp.thejaingroup.com",
         :domain      =>"thejaingroup.com",
         :port        => 587,
       :user_name   =>"debasish@thejaingroup.com",
        :password    =>"************"
        :authentication =>"plain"
       }

and my view is .. user_registration.text.erb ---is

            Hi sir you successfully Completed signed..........!

my have a error msg after running this apps.. SocketError in UsersController#create getaddrinfo: The requested name is valid, but no data of the requested type was found.

Rspec: uninitialized constant Devise::Controllers::SignInOut (NameError)

I am getting uninitialized constant Devise::Controllers::SignInOut (NameError) error whenever i try to execute the controller specs. i can start the webbrick server without any issue but getting this error only while executing rspc test cases.

below is the error that i am getting

C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/devise-3.4.1/lib/devise/con
trollers/helpers.rb:6:in `<module:Helpers>': uninitialized constant Devise::Cont
rollers::SignInOut (NameError)
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/devise-3.4.1/l
ib/devise/controllers/helpers.rb:4:in `<module:Controllers>'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/devise-3.4.1/l
ib/devise/controllers/helpers.rb:2:in `<module:Devise>'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/devise-3.4.1/l
ib/devise/controllers/helpers.rb:1:in `<top (required)>'
        from E:/Onspot-algo-git/onspot_development/lib/devise.rb:260:in `<module
:Devise>'
        from E:/Onspot-algo-git/onspot_development/lib/devise.rb:8:in `<top (req
uired)>'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.12
/lib/bundler/runtime.rb:76:in `require'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.12
/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.12
/lib/bundler/runtime.rb:72:in `each'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.12
/lib/bundler/runtime.rb:72:in `block in require'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.12
/lib/bundler/runtime.rb:61:in `each'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.12
/lib/bundler/runtime.rb:61:in `require'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/bundler-1.7.12
/lib/bundler.rb:134:in `require'
        from E:/Onspot-algo-git/onspot_development/config/application.rb:20:in `
<top (required)>'
        from E:/Onspot-algo-git/onspot_development/config/environment.rb:2:in `r
equire'
        from E:/Onspot-algo-git/onspot_development/config/environment.rb:2:in `<
top (required)>'
        from E:/Onspot-algo-git/onspot_development/spec/rails_helper.rb:3:in `re
quire'
        from E:/Onspot-algo-git/onspot_development/spec/rails_helper.rb:3:in `<t
op (required)>'
        from E:/Onspot-algo-git/onspot_development/spec/controllers/home_spec.rb
:1:in `require'
        from E:/Onspot-algo-git/onspot_development/spec/controllers/home_spec.rb
:1:in `<top (required)>'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/lib/rspec/core/configuration.rb:1361:in `load'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/lib/rspec/core/configuration.rb:1361:in `block in load_spec_files'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/lib/rspec/core/configuration.rb:1359:in `each'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/lib/rspec/core/configuration.rb:1359:in `load_spec_files'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/lib/rspec/core/runner.rb:106:in `setup'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/lib/rspec/core/runner.rb:92:in `run'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/lib/rspec/core/runner.rb:78:in `run'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/lib/rspec/core/runner.rb:45:in `invoke'
        from C:/RailsInstaller/Ruby2.0.0/lib/ruby/gems/2.0.0/gems/rspec-core-3.4
.4/exe/rspec:4:in `<top (required)>'
        from C:/RailsInstaller/Ruby2.0.0/bin/rspec:23:in `load'
        from C:/RailsInstaller/Ruby2.0.0/bin/rspec:23:in `<main>'

below is my home_spec.rb file

require 'rails_helper'
RSpec.describe :HomeController , :type => :controller do
  describe "Get #index" do
    it "should render template index" do
      get :index
      expect(response).to render_template("index")
    end
  end
end

Rails simple_form object_id association

In my app I have lots of model: (products belongs_to creator, creators belongs_to compagnie, compagnies belongs_to SEO, SEOs belongs_to user)

in my first Seoscontroller I have that:

def create
 @seo = current_user.seos.build(seo_params)
   if @seo.save
    redirect_to search_path
   else
    render :new
   end
end

(Controller work find!)

In the Compagniescontroller I think (but not work:[ )

def create
  seo = Seo.find(params[:seo_id])
   @compagnie = seo.compagnies.build(compagnie_params)
  if @compagnie.save
   redirect_to search_path
  else
   render :new
  end
end

and in my simple_form....

<%= simple_form_for @compagnie(seo_id: seo.id) do |f| %>
<% end %>

I search a solution for associate my model id to the controller and the simple_form_for

(my rails error: RuntimeError at /compagnies/new Association :seo_id not found)

Thanks

mercredi 13 juillet 2016

How long should a Microsofl Azure machine Learning API take to respond?

I've been trying to use a web app made in Ruby on Rails to access Microsoft's machine learning API. I already designed the API and deployed it as a web service, but all calls I have made so far have timed out and exceeded Heroku's 30 second limit. Is this a sign that something in my implementation is wrong, or is it normal to take that long and I should go for an asynchronous approach using Blobs instead?

Here is my sample HTTP post code:

def post
    url = @api_url
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    @request = Net::HTTP::Post.new(@api_url)
    @request.set_form_data({"Authorization" => "Bearer #{@api_key}", "Content-Length" => "#{@payload.length}", "Content-Type" => "application/json", "Accept" => "application/json"})
    @request.body = @payload
    resp = http.request(@request)
end

Voice response based on given voice input

I'm trying to get a voice based response for my web app. For this I have Googled and found the Annyang! Javascript library. Wiht the help of this library I was able to alert some message based on the voice command given by the user.

But anyone can please help me how can I get a voice response instead of UI response for a given user voice input?

Here is the code I'm using for getting a UI response for given voice commands.

<script>
$(document).ready(function(){
    if (annyang) {
        var commands = {
            'I am *name': function(name) {
               alert('Hello! '+ name + ' Please try saying "tell me your address"');          

            },

            'Tell me your address': function() {
              alert('Hey, we are at hyderabad kavuri hills. Should I mail it for you?');
              alert('Should I mail it for you?');
            },


            'yes': function(){
             alert('Please tell your mail id');
            },

            'my email is *email': function(email){
              alert('Mail has been sent to " +email)  
              alert('Okay, Thank you for visiting!')
            }

        };

        annyang.addCommands(commands);
        annyang.debug();
        annyang.start(); 
    }
});
</script>

can i optimise this code more? it needs code review.

    every 1.minute do
      runner "DailyNotificationChecker.send_notifications"
    end

this is whenever gem scheduler

    class DailyNotificationChecker

     def self.send_notifications
            puts "Triggered send_notifications"
            expiry_time = Time.now + 57
            while (Time.now < expiry_time)
                if RUN_SCHEDULER == "true" || RUN_SCHEDULER == true
                  process_notes
                end
              sleep 4 #seconds
            end
          end

          def self.process_notes
            notes = nil
            time = Benchmark.measure do
              Note.uncached do
                notes = Note.within_2_mins.unprocessed
                if notes.present?
                  note_ids = notes.pluck(:id)
                  note_hash = {}
                  note_hash[:note_ids] = note_ids.to_json
                  url = URI.parse(PROCESS_NOTE_API_URL)
                  resp, data = Net::HTTP.post_form(url, note_hash)
                  notes.each do |note|
                     puts "note_id = #{note.id}"
                     puts "processed #{note.processed}"
                    RealtimeNotificationChecker.perform_async(note.user_id,"note_created","TempUserNote",note.id)
                  end
                end
              end
            end
              puts "time #{time}"
          end
end

My purpose is I am trying to run realtime notifications. If a user creates a note in app then within 4 seconds I will send him a push notification.

so I run a cron job every 1 minute and hit the method send_notifications in my DailyNotificationChecker class. Now this is supposed to run a method process_notes every 4 seconds. every new note that is created is set processed = 0 flag. and I retrieve every unprocessed flag not more than 2 mins old and perform my operation on it.

the line

note_ids = notes.pluck(:id)
 note_hash = {}
 note_hash[:note_ids] = note_ids.to_json
 url = URI.parse(PROCESS_NOTE_API_URL)
 resp, data = Net::HTTP.post_form(url, note_hash)

gets all the note_ids that are unprocessed and sends them to master server to mark them processed = 1 so that in next 4 second hit these notes dont come again to processing list.

Then I loop in every note and send them in background to send push notificaion

    notes.each do |note|
      RealtimeNotificationChecker.perform_async(note.user_id,"note_created","TempUserNote",note.id)
    end

but i guess something is wrong here. As when I have more than 2 notes in to be processed it doesn't sends notification to all users.

Can someone suggest whats wrong and required

Note: I may have more than 10-15 notes to be processed within 4 sec. I am using sucker punch gem for background jobs.

Pass token from form

I have build a login api in which when users login he will get a token .And by using that token i am able to access other apis .

Authorization Token token=sadfghjkjhgfdsasdfghjgf

Like this I pass token by adding in header on each page.In my application controller I have added before_action :authenticate_user .So my question is I am building a form now and i need to pass the token which i have given above .This is not the form authenticity token so don't be confuse with that .I have search a lot but didn't got any relevant answer

Creating HTML test report with Ruby using test-unit-runner-html

I am working on Ruby with Selenium and Watir. I have implemented Test-Unit, now I have a need to implement HTML Test Report. I have gone through test-unit-runner-html, but not so lucky. Can somebody help me implementing test-unit-runner-html with my project. Suppose there is a suite containing different test cases and I have to implement on it.

ruby syntax error :

I have a ruby block that seems to work independently but as I put it in a ruby code sample it fails with syntax error :

code :

9 def get_version(name, user, pass, type, organization, art_module, repos, version)
10  puts case
11  when type.match(/snapshot$/i)
12    p version
13    when version.match(/latest$/i)
14         string_object = open("http://ift.tt/2aaXKk0}", :http_basic_authentication=>["#{user}", "#{pass}"])
15         json_file = JSON.parse(string_object.read)
16         version_array = Array.new
17         json_file["results"].each do |version|
18           version_array.push(version["version"].sub /-.*$/, '')
19         end
20         #p unique_versions=(version_array.uniq).max
21    else
22         p "here"
23         string_object = open("http://ift.tt/2aaXKk0}", :http_basic_authentication=>["#{user}", "#{pass}"])
24         json_file = JSON.parse(string_object.read)
25         version_array = Array.new
26         json_file["results"].each do |version|
27           version_array.push(version["version"].sub /-.*$/, '')
28         end
29         p unique_versions=(version_array.uniq).min
30    end
31  when type.match(/release$/i)
32  ...


SyntaxError
==> default: -----------
==> default: C:\vagrant-chef\a2c27477ebffe71b9594bbbb58557887\cookbooks\dj_productivity_any\providers\dj_artifactory_version.rb:26: syntax error, unexpected keyword_do_block, expecting keyword_end
==> default:          json_file["results"].each do |version|
==> default:                                      ^
==> default: C:\vagrant-chef\a2c27477ebffe71b9594bbbb58557887\cookbooks\dj_productivity_any\providers\dj_artifactory_version.rb:30: syntax error, unexpected keyword_end, expecting end-of-input

Edited to include line numbers

Rails 3.2 fields_for not showing

I use gem 'nested_form' in rails 3.2

Models:

meeting_agenda.rb:

class MeetingAgenda < ActiveRecord::Base
  has_many :meeting_questions, :inverse_of => :meeting_agenda
  accepts_nested_attributes_for :meeting_questions, allow_destroy: true
  attr_accessible :meeting_questions_attributes
end

meeting_question.rb:

class MeetingQuestion < ActiveRecord::Base
  has_one :meeting_answer, :inverse_of => :meeting_question
  accepts_nested_attributes_for :meeting_answer
  attr_accessible :meeting_answer_attributes
end

meeting_answer.rb

class MeetingAnswer < ActiveRecord::Base
  belongs_to :meeting_question
end

Controller:

class MeetingProtocolsController < ApplicationController

  def new
    @agenda = MeetingAgenda.new
  rescue => error
    render_403
  end


  def create
    @agenda = MeetingAgenda.new(params[:meeting_agenda])

    if @agenda.save && protocol.save
      flash[:notice] = l(:notice_successful_create)
      redirect_to action: 'show', id: @agenda.id
    else
      render action: 'new'
    end
end

View:

new.html.haml:

= nested_form_for @agenda do |f|
# ...

  = f.fields_for :meeting_questions do |question|
    # ...

    # Fields for answer is not showing!
    = question.fields_for :meeting_answer do |answer| # <-- blank

      %p # <-- blank
        = answer.label :reporter_id_is_contact, t(:label_meeting_question_user_is_contact) # <-- blank
        = answer.check_box :reporter_id_is_contact; # <-- blank

        = question.link_to_remove l(:button_delete) # <-- blank

  = f.link_to_add l(:button_add), :meeting_questions
  = submit_tag l(:button_create)

I`m try to resolve this problem for 3 days =( has_one relation with accepts_nested_attributes_for is empty. Help me, please!

Change html output from ransack select

I'm using the ransack gem in one of my projects to handle searching. It gets the job done without a lot of code, but I want to change the HTML output for the select boxes and I can't seem to find a way to easily do that. The code I'm using looks like this

# index page

<%= search_form_for @search, url: search_pages_path, method: :post do |f| %>
  <%= f.condition_fields do |c| %>
    <%= render "condition_fields", f: c %>
  <% end  %>
  <%= link_to_add_fields "Add conditions", f, :condition %>
  <div class="search-row">
    <span>Sort:</span>
    <%= f.sort_fields do |s| %>
    <div class="input-group">
      <h1>Sort</h1>
      <%= s.sort_select %>
      <h1>after sort</h1>
    </div>
    <% end %>
    <%= f.submit class: 'btn btn-sm color-3' %>
  </div>
<% end %>

# condition_fields

<div class="search-row">
  <%= f.attribute_fields do |a| %>
  <div class="input-group">
    <label class="select">
      <%= a.attribute_select associations: [:category] %>
    </label>
  </div>
  <% end %>
  <div class="input-group">
    <label class="select">
      <%= f.predicate_select compounds: false, only: %i(cont not_cont eq not_eq blank null) %>
    </label>
  </div>
  <%= f.value_fields do |v| %>
    <div class="input-group">
      <%= v.text_field :value, class: "input" %>
    </div>
  <% end %>
  <div class="action-group">
    <%= link_to "Remove", "#", class: "link color-1 remove_fields" %>
  </div>
</div>

I've looked at the source code for the ransack FormBuilder class and it looks like most everything is coming through the search_fields method which seems to create a custom template from the inherited FormBuilder class.

Basically, I want the output from the method calls to change from something like this:

<select name="q[c][0][a][0][name]" id="q_c_0_a_0_name">
  <option value="bloggerTier">Blogger Tier</option>
  <option value="category_name">Primary Category</option>
  ...
</select>

To something like this:

<ul name="q[c][0][a][0][name]" id="q_c_0_a_0_name">
  <li value="bloggerTier">Blogger Tier</li>
  <li value="category_name">Primary Category</li>
  ...
</ul>

But I'm not sure how feasible that is without messing with the gem source code like is done in this other related article or if there's a simpler way that I'm missing.

How can I skip the specific methods from brakeman scanning process + Rails

I am using the brakeman for security check in my app. I want to skips some methods those are false positive and I Mark Methods as Safe, but I want to add a flag to method to skip that method while brakeman scanning the application.

Example:

class User < ActiveRecord::Base

  # I want to skip this method when brakeman scan the application
  # Kind of `flag` to skip the method
  def profile
    # ..
  end

  def company
    #..
  end
end

I want to add a file where I can manage that which tag need to be skip.

Do any one know how can I do that? Your help is much appreciated.

mardi 12 juillet 2016

How to display validation error inside of an input field?

In my rails app I'm using simple_form. I need to get the error messages in the input field instead of it being displayed on the side, like the image shown below.

enter image description here

How can I do this?

Rails route not found, but exists in rake routes

I'm trying to create a new resource called a Snapshot, to consolidate a couple of actions that probably should be a resource of their own rather than cluttering up the ProjectsController. I'm sure I've set everything up correctly, but Rails doesn't recognise the route.

Here's the relevant excerpt from my routes.rb:

resources :projects do
  resources :snapshots, only: [:create, :update]
end

It shows up when I run rake routes just fine:

project_snapshots POST     /projects/:project_id/snapshots(.:format)                                          snapshots#create
 project_snapshot PATCH    /projects/:project_id/snapshots/:id(.:format)                                      snapshots#update
                  PUT      /projects/:project_id/snapshots/:id(.:format)                                      snapshots#update

But in the rails console, I don't get any joy:

r = Rails.application.routes
=> #<ActionDispatch::Routing::RouteSet:0x007faa06b5b730>

r.recognize_path "/projects/1234/snapshots"
ActionController::RoutingError: No route matches "/projects/1234/snapshots"
    from /Users/merus/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/actionpack-4.2.0/lib/action_dispatch/routing/route_set.rb:840:in `recognize_path'
    from (irb):4
    from /Users/merus/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start'
    from /Users/merus/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in `start'
    from /Users/merus/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /Users/merus/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /Users/merus/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

I've tried replacing 'resources' with 'resource' just in case that doesn't work; no dice. What's wrong here?