Friday, September 30, 2016

How do I use a before_action type callback in ActiveRecord Models | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

How do I use a before_action type callback in ActiveRecord Models | Fixed issues


How do I use a before_action type callback in ActiveRecord Models

Posted: 30 Sep 2016 07:53 AM PDT

I have a database model that doesn't actually have any data since all my User informatio is stored on a third party authentication service. I want to be able to use the Model like a regular one, so upon load, I fetch all the information from the API and store it in an instance variable.

How do I setup a before_action like callback for my model? Is there a Ruby way to do this?

class Auth0User < ApplicationRecord    before_action set_instance_variables      validates :auth0_id, presence: true,                         uniqueness: true      def info(key = nil)      key.nil? ? @user : @user[key.to_s]    end      private      def set_instance_variables      @user ||= auth0_api.user auth0_id    end      def auth0_api      Auth0Client.new(        client_id: Rails.application.secrets.auth0_client_id,        token: Rails.application.secrets.auth0_management_jwt,        domain: Rails.application.secrets.auth0_domain,        api_version: 2      )    end  end  

Rails app instances & memory usage

Posted: 30 Sep 2016 07:35 AM PDT

Is the memory usage for number of Rails app instances linear?

I have a rails app on heroku that normally runs on a a couple dynos with 2 app instances per. We've been offered a free month of a Performance-L dyno so I've been playing around with the web concurrency a little bit.

I noticed that initially moving from 2 to 4 seemed to double the memory usage. But as I continued to increase the app instances, the increase in memory slowed. Currently I have 40 app instances running on this 14GB machine and am only using about 6GB. Is it simply a matter of not enough traffic for them all to be initialized?

What else is at play here and what are my limitations to how many instances I can run on this Performance-L Dyno?

Devise Ajax session for confirmable user

Posted: 30 Sep 2016 07:34 AM PDT

I have an ajax form for users sign up. I have problem when i try to login user which isn't confirmed. It never reach's create action from session controller if i enter valid username and password, if i write wrong password for user, i get inside create action and return good response from invalid_login_attempt method.

Sessions controller:

class SessionsController < Devise::SessionsController      def create      debugger      resource = Bbp::User.find_for_database_authentication(email: params[:user][:email])      return invalid_login_attempt unless resource      return invalid_login_attempt unless resource.valid_password?(params[:user][:password])      return confirmation_needed if resource.confirmed_at.nil?      if resource.valid_password?(params[:user][:password])        sign_in :user, resource        return render nothing: true      end        invalid_login_attempt    end       protected      def invalid_login_attempt        render json: "Wrong username or password", status: 401      end        def confirmation_needed        render json: "You need to confirm your email before you can continue", status: 401      end    end  

And my form is:

<h2>Sign in</h2>  <div class="message-success-field user-sign-in-row"></div>  <%= form_for(resource, as: resource_name, url: '/admin.json',html: {id: 'new_user_session'}, remote: true ) do |f| %>    <div class="form-group">      <%= f.email_field :email, class: "form-control", placeholder: "Email", autofocus: true %>    </div><!-- form-group -->    <div class="form-group">      <%= f.password_field :password, class: "form-control", placeholder: "Password #{'(' + @minimum_password_length.to_s + ' characters minimum)' if @minimum_password_length}", autocomplete: "off" %>    </div><!-- form-group -->    <% if devise_mapping.recoverable? %>      <small><%= link_to "Forgot your password?", new_password_path(resource_name) %></small><br />    <% end %>    <% if devise_mapping.rememberable? %>      <div class="field">        <%= f.check_box :remember_me %>        <%= f.label :remember_me %>      </div>    <% end %>    <%= f.button "Sign in", class: "form-control btn btn-success" %>    <p>Or connect via Facebook</p>    <%= link_to "Sign in with facebook", "/auth/facebook", class: "form-control btn btn-primary" %>  <% end %>  <script>    $(document).ready(function() {      $('#new_user_session')      .bind('ajax:success', function(response, evt, data, status, xhr) {        $('div.user-sign-in-row').empty()        $('div.user-sign-in-row').append("You are successfully logged in")      })      .bind("ajax:error", function(evt, xhr, status, error) {        $('div.user-sign-in-row').empty()        $('div.user-sign-in-row').append(xhr.responseText)      });    });  </script>  

I think this happens because somewhere before create, devise checks if user is comfirmable, but i can't find where is that. I also set that sessions controller respond to html and json.

What can be issue?

Better? design software to build a modules/plans architecture

Posted: 30 Sep 2016 07:25 AM PDT

It is very common today found systems with sign plans, like Free Plan, Hobby Plan, etc. It's seems easy to build, just add some extra validation in the plan that you did sign. But, how to build a maintainable software for each plan? Write IFs and ELSEs on models, controllers & views?

Using RoR, I think the better way is using modules. Like, you are the Free Plan, so add the Plans::Free in controllers and models to do specifics validations.

I cannot think a better idea to excludes the IFs ELSEs.

Is there a better design? Of course is there, but which?

Rails 4: Ajax request calls function and returns value without redirect

Posted: 30 Sep 2016 07:35 AM PDT

I have a rails controller function that calls out to a model function to fetch data and return that data. I am trying to use ajax to make the function call and don't want any redirect as all I care about are the values being returned. How can I accomplish this without reloading the page / getting a missing template error?

Controller

def update_sales      @data = ControllerName.function_name()      return @data  # What I want      redirect_to path_name # what I don't want  end  

Model

def self.function_name      ...      ...      return data  end  

Ajax

$.get("/update_sales").done(function(data){      console.log(data);      // I would set html attribute to data but I get missing template error  })  

Netsuite Authentication with Oauth 1.0 Restlet signature on ruby on rails

Posted: 30 Sep 2016 07:13 AM PDT

I have a problem with authentication with Oauth 1.0 for Netsuite, i made a code with RFC standard but without success.

With postman I get working with same tokens etc.. but I dont know why the signature is not the same on Postman and my rails with the same nonce and timestamp.

I think the position or something else I have are incorrect...

This is my code:

require 'uri'  require 'cgi'  require 'openssl'  require 'base64'  require 'net/http'    consumer_key = 'xxxxxxx'  consumer_secret = 'zzzzzzz'  token = 'rrrrr'  token_secret = 'eeeee'  realm = '3474661'  method = 'GET'  uri = URI.parse "https://rest.na1.netsuite.com"  script = "/app/site/hosting/restlet.nl?script=537&amp;deploy=1"    def generate_nonce(size=10)    rand(10 ** size).to_s.rjust(size,'0')  end    def params(consumer_key, token, realm)    params = {      'realm' => realm,      'oauth_consumer_key' => consumer_key,      'oauth_nonce' => 'GLk4E8', #generate_nonce,      'oauth_signature_method' => 'HMAC-SHA1',      'oauth_token' => token,      'oauth_version' => '1.0',      'oauth_timestamp' => '1475240334'##Time.now.to_i.to_s,    }  end    def signature_base_string(method, uri, params)    encoded_params = url_encode("oauth_consumer_key=#{params['oauth_consumer_key']}&oauth_nonce=#{params['oauth_nonce']}&oauth_signature_method=#{params['oauth_signature_method']}&oauth_timestamp=#{params['oauth_timestamp']}&oauth_token=#{params['oauth_token']}&oauth_version=#{params['oauth_version']}")    encoded = method + '&' + url_encode(uri) + '&' + encoded_params    puts encoded    encoded  end    def url_encode(string)     CGI::escape(string)  end    def sign(key, base_string)    digest = OpenSSL::Digest.new('sha1')    hmac = OpenSSL::HMAC.digest(digest, key, base_string)    Base64.encode64(hmac).chomp.gsub(/\n/, '')  end    def header(params)    header = "OAuth "    params.each do |k, v|      header += "#{k}=\"#{v}\","    end    header.slice(0..-2)  end    def request_data(header, uri, method, script, post_data=nil)    http = Net::HTTP.new(uri.host, uri.port)    http.use_ssl = true    http.verify_mode = OpenSSL::SSL::VERIFY_NONE    if method == 'POST'    else      resp, data = http.get(script, {        'Authorization' => header,        "Content-Type" => "application/json; charset=utf-8"         })    end    puts resp    resp.body  end    params = params(consumer_key, token, realm)    puts uri.to_s + script      signature_base_string = signature_base_string(method, uri.to_s + script, params)    puts ""  puts signature_base_string  puts ""    signing_key = consumer_secret + '&' + token_secret  params['oauth_signature'] = sign(signing_key, signature_base_string)    puts params    header_string = header(params)    puts ""  puts header_string  puts ""        response = request_data(header_string, uri, method, script)    puts response  

I got this error:

{"error" : {"code" : "INVALID_LOGIN_ATTEMPT", "message" : "Invalid login attempt."}}  

If anybody can help me to find what im doing wrong, i will be grateful.

Thanks!

How to add ApplicationController in Rails Engine?

Posted: 30 Sep 2016 07:06 AM PDT

I Have tried

require_dependency "try_anything/application_controller" as mentioned in rails engine documentation but it's not working. Followed below documentation but getting undefined require_dependency error Rails Engine Documentation

how to update seed.rb on heroku rails app

Posted: 30 Sep 2016 07:39 AM PDT

I have two roles option in my registration page seller and buyer i was using the seed.rb file for this but know i changed the names to seller and customer and pushed it to heroku by doing

heroku run rake:db seed  

Everything worked well but now on my registration page am getting four roles options seller, buyer, Seller, Customer I want only the Seller And Customer one what should i do

my seed.rb

['Customer', 'Seller'].each do |role|    Role.find_or_create_by({name: role})  end  

Error with form_for when trying to edit - Rails 4

Posted: 30 Sep 2016 06:48 AM PDT

I keep getting an error when trying to edit and the error stems from the form_for and I'm not sure how to fix it.

Landlord Addresses Controller Edit Action:

def edit  end  

Edit Link To:

<tbody>  <% @landlord_addresses.each do |landlord_address| %>    <tr>      <td><%= link_to 'Edit', edit_landlord_address_path(landlord_address) %></td>    </tr>  <% end %>  

Error:

enter image description here

Where should I check after I set up environment variables for rails cron named “Whenever”?

Posted: 30 Sep 2016 06:46 AM PDT

CentOS 6.8
Ruby on Rails
Cron: Whenever

I set up environment variables for DB name, DB password and DB host. I am sure those variables show up with env command.

But I cannot use them in rails codes or yaml files like <%= ENV["DB_NAME"] %>. They are nil. When I put DB name in database.yml directly, it works. There are logs saying "No database selected" something like that. I understand the logs because <%= ENV["DB_NAME"] %> is nil but I don't know how to solve it.

Generally, Where should I check if my setting is fine for rails cron named "Whenever"? or Could you tell me how to set up correctly?

double polymorphic association with same tables? any idea on how to preload them?

Posted: 30 Sep 2016 06:33 AM PDT

I have CallSession table. it has polymorphic associations:

class CallSession < ActiveRecord::Base    belongs_to :callable, polymorphic: true    belongs_to :calleeable, polymorphic: true  end  

CallSession has callable_type,callable_id,calleeable_type and calleeable_id.

the members of callable assoc are Doctor table and Consumer table, and calleeable assoc has Doctor and Consumer table. (yeah the same tables)

now, I need to query CallSession where its callable Email is different from its calleeable Email (Both Doctor and Consumer has Email,both can be callable or calleeable). One email can be used for both Doctor and Consumer object.

any idea on how to query it in one Scope with preloads to avoid N+1? thanks in advance! at worst I will store the callable.email and calleeable.email in new columns.

Render js if variable length is 0 (rails)

Posted: 30 Sep 2016 06:47 AM PDT

I am defining a variable in my controller method. I want to render js if the size of the variable is zero.

My code is:

def department    @department = Department.all  end  

when the above method is called department.html.erb is rendered right now

I want or do something like this:

def department    @department = Department.all    if @department.count > 0      render :html => html-template-name    else      render :js => "alert('No department available');"    end  end  

This should render html if count is greater than 0 else should render js. What should be the syntax of render html part?

How to take value for Object result in ruby on rails

Posted: 30 Sep 2016 06:32 AM PDT

I want to print specific value from object result. here is i am execute SQL query and take all data from View tables, All data coming from "Employee_Information" view(table). hr_controller.rb

class HrController < ApplicationController      def internal_employee_page              @employees = MysqlConnection.connection.select_all("SELECT * FROM Employee_Information")    end   end  

internal_employee_page.html.erb this is my first view

<div id="job_details">      <% @employees.each do |emp| %>          <%= render partial: "hr/employee_details", locals: {emp: emp} %>      <% end %>                 </div>  

_employee_details.html.erb this is my second view

<h3> User Name : <%= emp%> </h3>  

like this I am trying to print all value then I got following result enter image description here I want to print each value I tried this also in my second view

<h3> User Name : <%= emp.full_name%> </h3>  

But I got Error: enter image description here Please help me I tried every thing according to my knowledge, where am I wrong and what is problems

Rails on Elastic Beanstalk, Can't do a load balancer health check

Posted: 30 Sep 2016 05:55 AM PDT

I am running a rails app on elastic beanstalk, my problem is that I cannot use the load balancer health check, as it checks via http, not https. I have config.force_ssl set to true, and don't really want to change it, since it means I have 100% ssl coverage, HSTS, and secure cookies. I have setup a controller to check at /health and can access this via curl. There seems to be a contradiction between what is shown in elastic beanstalk (EC2 Instance Health Check), where I can only change the path and some timings, and the health check in the load balancer in EC2, where I can change the ping protocol, port and path to what I want, but this seems to have no effect other than causing a 503 error.

Ping Protocol: https   Ping Port: 443   Ping Path: /health  

The load balancer has ports 80 and 443 open but redirects from 80 to 443 due to force_ssl.

Does anyone know of the correct settings to get around this, as I won't be able to scale the application without it?

Thank you

Eamon

Cant Send email from outlook using ruby script

Posted: 30 Sep 2016 05:47 AM PDT

so this is code works fine with yahoo and gmail but it throws an error when i run it with using outlook smtp

  `require 'mail'           options =   {              :address        => 'smtp.live.com',             :port           => '587',             :authentication => :login,             :user_name      => ENV['mymail@outlook.com'],             :password       => ENV['mypassword'],             :enable_starttls_auto => true                     }          Mail.defaults do  delivery_method :smtp, options  end        Mail.deliver do    to 'test@gmail.com'  from 'mymail@outlook.com'  subject 'test'  body 'outlook'  end  

`

when i execute this script it gives me "untitled.rb: end of file reached (EOFError)" this error ,i would really appreciate your help

Must pass hash error when passing params to devise registration/ sign up

Posted: 30 Sep 2016 05:48 AM PDT

This is the error that is displaying

When assigning attributes, you must pass a hash as an argument.  

I am trying to pass params through a URL something like this /users/sign_up?account=571917355

registrations_controller.rb

def new    @user = User.new(params[:account])  end  

Is devise doing something that isn't allowing this to work? I've searched, but nothing out there seems to help fix the error. I'm not even really sure what this error means.

How to get list of expiring/dropping Domains

Posted: 30 Sep 2016 06:40 AM PDT

How to get the list of Expiring or dropping domains ? Just like Park.io

Thanks in advance.

API call response fail error-line : The request sent by the client was syntactically incorrect rails 4

Posted: 30 Sep 2016 06:37 AM PDT

I am trying to call an API for salesmanago in my lib file. below is my lib file :

require 'httparty'    class SalesManago    include HTTParty    debug_output STDOUT # to check output of request      default_params :output => 'json'    format :json       def self.add_contact_to_sales_manago(login_user)      headers = {"Accept" => "application/json, application/json", "Content-Type" => "application/json;charset=UTF-8"}      email_addr = login_user.email      full_name = login_user.full_name      phone_number = login_user.mobile      state = login_user.state_county      options = {}      options["clientId"] = Client_ID      options["apiKey"] = MicroSite_Key      current_time = Time.now      request_time = current_time.strftime("%Y%m%d%H%M%S")      sha_string = MicroSite_Key + Client_ID + API_Secret      options["sha"] = Digest::SHA1.hexdigest(sha_string)      options["contact"] = { :email => email_addr, :name => full_name, :phone => phone_number, :state => state }      options["requestTime"] = request_time      api_response = post("http://www.salesmanago.pl/api/contact/upsert", :query => options, :headers => headers)    end  end  

This is how I am calling my API. I am also debugging output using 'debug_output STDOUT'. In response I am getting an error which says :

'The request sent by the client was syntactically incorrect.'  

Can't understand what's going wrong!

Below is the request response :

opening connection to www.salesmanago.pl:80...    opened  <- "POST /api/contact/upsert?output=json&clientId=tka09bdgoljf3gkt&apiKey=7wcmgejg1v0qyfqlqtupzekm8gd3ts3z&sha=94f68fe07aa57f63f8faa524f017ccbd974381cd&contact[email]=pravin%40ascratech.in&contact[name]=Pravin%20Karale&contact[phone]=&contact[state]=&requestTime=20160930173051 HTTP/1.1\r\nAccept: application/json, application/json\r\nContent-Type: application/json;charset=UTF-8\r\nConnection: close\r\nHost: www.salesmanago.pl\r\nContent-Length: 0\r\n\r\n"  <- ""  -> "HTTP/1.1 400 Bad Request\r\n"  -> "Date: Fri, 30 Sep 2016 12:16:47 GMT\r\n"  -> "Server: Apache\r\n"  -> "Content-Language: en\r\n"  -> "Content-Length: 968\r\n"  -> "Vary: Accept-Encoding\r\n"  -> "Connection: close\r\n"  -> "Content-Type: text/html;charset=utf-8\r\n"  -> "Set-Cookie: SERVERID=A; path=/\r\n"  -> "\r\n"  reading 968 bytes...  -> "<html><head><title>Apache Tomcat/7.0.56 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 400 - </h1><HR size=\"1\" noshade=\"noshade\"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect.</u></p><HR size=\"1\" noshade=\"noshade\"><h3>Apache Tomcat/7.0.56</h3></body></html>"  read 968 bytes  Conn close  

How to create an association between two models with form choice field using Active Admin, Paperclip in Rails 5.0.1

Posted: 30 Sep 2016 05:52 AM PDT

Scenario

I am building a similar App like AirBnB but the difference is that only the Admin can add new Apartments, Rooms, Houses etc. Therefore I created an Admin Panel with the activeadmin gem. I am now adding the image upload system into activeadmin so I am using the paperclip gem. I have two models "room" and "photo". The photo model has an "image" column. The room model has an "listing_name" column.

room.rb (app/models)

class Room < ApplicationRecord      has_many :photos  end  

photo.rb (app/models)

class Photo < ApplicationRecord    belongs_to :room      has_attached_file :image, styles: { medium: "300x300>", thumb: "100x100>" }    validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/  end  

If I am not putting a custom form inside "photo.rb (app/admin)" I can associate the image to a room by default. But I can't upload a picture! This looks like this:

enter image description here

So I changed the "photo.rb (app/admin)" file into this:

photo.rb (app/admin)

ActiveAdmin.register Photo do     permit_params :image       form :html => {:multipart => true} do |f|        f.inputs "Project Details" do            f.input :image, :required => false, :as => :file        end        f.actions     end       show do |ad|        attributes_table do           row :image do              image_tag(ad.image.url(:thumb))           end        end     end  end  

With this form I can upload a picture into the image column but I can't associate it to a room and the edit view does not give me a preview of a picture as the show view does:

enter image description here

enter image description here

enter image description here

Questions:

  1. How can I have a preview of the image in the admin edit view?

  2. How can build a form to associate an image to a room by choosing the listing_name of the room?

Something like this:

enter image description here

Thank you in advance for your help.

How to modify the normal credit card details form to Braintree dropin-ui form in Rails?

Posted: 30 Sep 2016 05:00 AM PDT

I am having a registration page where user will enter personal info along with credit card info. My requirement is to display the credit card info as Braintree dropin UI. I registered with braintree sandbox and having all the keys / credentials.

Now the fields like card number, expiry date, etc; in the above form has to be in braintree drop-in ui look (and here itself the credit card number is validated by braintree whether it is correct or no). Also these fields are stored in a table where Credit card number is stored as xxxx-xxxx-xxxx-1000 and expiry date is stored as it is. How can I modify this form? Please help.

This is my form:

<%= semantic_form_for(@account, :url => account_create_path, :html => { :multipart => true, :class => 'billing'}) do |f| %>       <div class="section section-first">        <%= f.inputs :for => :user do |u| %>          <h3>Account Information</h3>            <%= u.input :name, :input_html => {:placeholder => "Name", :value => @account.user.name} %>          <%= u.input :email, :input_html => {:placeholder => "Email", :value => @account.user.email} %>        <% end %>      </div>          <div class="section">              <%= f.inputs :for => :creditcard do |c| %>              <h3>Credit Card Information</h3>              <%= c.input :brand, :selected => @creditcard.brand.nil? ? "visa" : @creditcard.brand, :label => "Credit Card", :as => :select, :class => 'dropkick', :include_blank => false, :collection => Saas::Config.gateway == "bogus" ? [['Bogus', 'bogus']] : [['Visa', 'visa'], ['MasterCard', 'master'], ['American Express', 'american_express'], ['Discover', 'discover']] %>              <%= c.input :number, :input_html => { :placeholder => "Card Number"}, :label => "Card Number", :as => :numeric %>                <li class="select required" id="account_creditcard_expiration_input">                  <label for="account_creditcard_expiration">Card Expires On<abbr title="required">*</abbr></label>                <%= c.select :year, (Time.now.year .. 10.years.from_now.year), :selected => @creditcard.year.nil? ? Time.now.year : @creditcard.year, :class => 'dropkick dd-small' %>                <%= c.select :month, [['1 - January', 1], ['2 - February', 2], ['3 - March', 3], ['4 - April', 4], ['5 - May', 5], ['6 - June', 6], ['7 - July', 7], ['8 - August', 8], ['9 - September', 9], ['10 - October', 10], ['11 - November', 11], ['12 - December', 12]], :selected => @creditcard.month.nil? ? "1" : @creditcard.month, :class => 'dropkick' %>              </li>                <%= c.input :verification_value, :label => "CVV Code", :input_html => { :placeholder => "CVV Code", :value => @creditcard.verification_value,                  :type => "password",                  :class => 'short' } %>              <% end %>    <% end %>  

I added gem 'braintree' to Gemfile and created a new file config/initializers/braintree.rb and added all the credentials / keys here. I added this line in layouts/application.html.erb:

<script src="https://js.braintreegateway.com/v2/braintree.js"></script>  

I added id to credit card section in my accounts/new form as:

<div class="section" id="dropin-container">          <%= f.inputs :for => :creditcard do |c| %>           ....................................  </div>  

and javascript as:

<script type="text/javascript">  $(document).ready(function(){    braintree.setup('sandbox_rc6qd77v_9pgjq29mtpxgp7m5', 'dropin', {    container: 'dropin-container'  });  </script>  

While integration testing, ActionController::ParameterMissing appears, despite logs to the contrary

Posted: 30 Sep 2016 05:26 AM PDT

I have installed Rails using the instructions from https://gorails.com/setup/ubuntu/16.04 on an Ubuntu 16.04 amd64 server. I used 'rbenv' rather than any of the other options.

I created a new application named 'testapp'.

I then executed:

$ rails generate scaffold Test name:string age:integer  

Then, I executed:

$ bin/rails generate integration_test tests_post  

I modified test/integration/tests_post_test.rb to read as follows:

require 'test_helper'    class TestsPostTest < ActionDispatch::IntegrationTest      test "can create an item" do      get "/tests/new"      assert_response :success      post "/tests",        params: { test: { name: 'Micky Mouse', age: 120 } }      assert_response :redirect      follow_redirect!      assert_response :success    end  end  

And then I executed:

rake test  

This gives me the following error:

Run options: --seed 24994    # Running:    .......E    Finished in 0.247049s, 32.3822 runs/s, 56.6689 assertions/s.      1) Error:  TestsPostTest#test_can_create_an_item:  ActionController::ParameterMissing: param is missing or the value is empty: test      app/controllers/tests_controller.rb:72:in `test_params'      app/controllers/tests_controller.rb:27:in `create'      test/integration/tests_post_test.rb:8:in `block in <class:TestsPostTest>'    8 runs, 14 assertions, 0 failures, 1 errors, 0 skips  

Yet, the relevant logging shows the following:

--------------------------------------  TestsPostTest: test_can_create_an_item  --------------------------------------  Started GET "/tests/new" for 127.0.0.1 at 2016-09-30 07:50:18 -0400  Processing by TestsController#new as HTML    Rendered tests/_form.html.erb (13.6ms)    Rendered tests/new.html.erb within layouts/application (16.4ms)  Completed 200 OK in 170ms (Views: 161.1ms | ActiveRecord: 0.0ms)  Started POST "/tests" for 127.0.0.1 at 2016-09-30 07:50:19 -0400  Processing by TestsController#create as HTML    Parameters: {"params"=>{"test"=>{"name"=>"Mickey Mouse", "age"=>"120"}}}  Completed 400 Bad Request in 0ms (ActiveRecord: 0.0ms)  

In development and in production, this gives no errors, only in test. I keep looking over examples I've seen online in other projects, but I don't see that I'm doing anything particularly out of the ordinary here. I created these specific steps to show the problem as simply as possible. Any ideas how to get this to work properly? Is there perhaps a bug in this version of rake (11.3.0)?

How to integrate Alexa Rank API/gem with Ruby on Rails?

Posted: 30 Sep 2016 04:58 AM PDT

I'm new to rails. I'm trying to integrate Alexa Rank API into my application. I don't know how to proceed? I did my best here, and it gives error:-

NameError: undefined local variable or method `access_key_id' for #

Any one tell me , how to consume a third party API like this into rails application. It would be greatful.I need to build a web ranking site with graph analysis.

Here is my code:- Client.rb

class Client < ActiveRecord::Base    attr_reader :access_key_id, :secret_access_key    def self.find_rank(site_name)      look_rank = Alexa::Client.new(access_key_id , secret_access_key).url_info(url: site_name)      return nil unless look_rank.rank        new_rank=new(name: look_rank.site_title, rank: look_rank.rank_by_country)      new_rank=new_rank.web_rank      new_rank    end    def rank      web_rank=Alexa::Client.new(access_key_id: access_key_id,                secret_access_key: secret_access_key).url_info(url: site_name).rank       return "#{web_rank}" if web_rank     end  

end

Here is Alexa rank gem code:- Url Info:-

  client = Alexa::Client.new(access_key_id: "key",                           secret_access_key:"secret")    url_info = client.url_info(url: "site.com")   Method Names:- rank, site_title, keywords etc..  

Switch from squlite3 to postgres to deploy on Heroku

Posted: 30 Sep 2016 04:49 AM PDT

My initial database is sqlite 3. But heroru doesn't support it and I have to switch to postgres sql. I tried to had the gem in the gemfile, and the deployment still failed.

/gemfile

source 'https://rubygems.org'    gem 'postgres', '~> 0.8.1'  group :development, :test do    gem 'sqlite3'  end  

extract from deployment logs failed :

...    Bundled gems are installed into ./vendor/bundle.  remote:        Post-install message from rdoc:  remote:        Depending on your version of ruby, you may need to install ruby rdoc/ri data:  remote:        <= 1.8.6 : unsupported  remote:        = 1.8.7 : gem install rdoc-data; rdoc-data --install  remote:        = 1.9.1 : gem install rdoc-data; rdoc-data --install  remote:        >= 1.9.2 : nothing to do! Yay!  remote:        Post-install message from haml:  remote:        HEADS UP! Haml 4.0 has many improvements, but also has changes that may break  remote:        your application:  remote:        * Support for Ruby 1.8.6 dropped  remote:        * Support for Rails 2 dropped  remote:        * Sass filter now always outputs <style> tags  remote:        * Data attributes are now hyphenated, not underscored  remote:        * html2haml utility moved to the html2haml gem  remote:        * Textile and Maruku filters moved to the haml-contrib gem  remote:        For more info see:  remote:        http://rubydoc.info/github/haml/haml/file/CHANGELOG.md  remote:        Post-install message from compass:  remote:        Compass is charityware. If you love it, please donate on our behalf at http://umdf.org/compass Thanks!  remote:        Post-install message from postgres:  remote:        ---------------------------------------------------------------------------  remote:        This is an old, deprecated version of the Ruby PostgreSQL driver that hasn't  remote:        been maintained or supported since early 2008.  remote:        You should install/require 'pg' instead.  remote:        If you need the 'postgres' gem for legacy code that can't be converted, you can  remote:        still install it using an explicit version, like so:  remote:        gem install postgres -v '0.7.9.2008.01.28'  remote:        gem uninstall postgres -v '>0.7.9.2008.01.28'  remote:        If you have any questions, the nice folks in the Google group can help:  remote:        ---------------------------------------------------------------------------  remote:        Post-install message from paperclip:  remote:        ##################################################  remote:        #  NOTE FOR UPGRADING FROM 4.3.0 OR EARLIER       #  remote:        ##################################################  remote:        Paperclip is now compatible with aws-sdk >= 2.0.0.  remote:        If you are using S3 storage, aws-sdk >= 2.0.0 requires you to make a few small  remote:        changes:  remote:        * You must set the `s3_region`  remote:        * If you are explicitly setting permissions anywhere, such as in an initializer,  remote:        note that the format of the permissions changed from using an underscore to  remote:        using a hyphen. For example, `:public_read` needs to be changed to  remote:        `public-read`.  remote:        For a walkthrough of upgrading from 4 to 5 and aws-sdk >= 2.0 you can watch  remote:        http://rubythursday.com/episodes/ruby-snack-27-upgrade-paperclip-and-aws-sdk-in-prep-for-rails-5  remote:        Post-install message from twitter-bootstrap-rails:  remote:        Important: You may need to add a javascript runtime to your Gemfile in order for bootstrap's LESS files to compile to CSS.  remote:        **********************************************  remote:        ExecJS supports these runtimes:  remote:        therubyracer - Google V8 embedded within Ruby  remote:        therubyrhino - Mozilla Rhino embedded within JRuby  remote:        Node.js  remote:        Apple JavaScriptCore - Included with Mac OS X  remote:        Microsoft Windows Script Host (JScript)  remote:        **********************************************  remote:        Bundle completed (47.33s)  remote:        Cleaning up the bundler cache.  remote: sh: 1: $: not found  remote: sh: 1: $: not found  remote:  !  remote:  !     Could not detect rake tasks  remote:  !     ensure you can run `$ bundle exec rake -P` against your app  remote:  !     and using the production group of your Gemfile.  remote:  !     This is an old, deprecated version of the Ruby PostgreSQL driver that hasn't  remote:  !     been maintained or supported since early 2008.  remote:  !       remote:  !     You should install/require 'pg' instead.  remote:  !       remote:  !     If you need the 'postgres' gem for legacy code that can't be converted, you can  remote:  !     still install it using an explicit version, like so:  remote:  !       remote:  !     gem install postgres -v '0.7.9.2008.01.28'  remote:  !     gem uninstall postgres -v '>0.7.9.2008.01.28'  remote:  !       remote:  !     If you have any questions, the nice folks in the Google group can help:  remote:  !       remote:  !  remote: /app/tmp/buildpacks/f6d48d8a14fccbb19c0c0402fca224929d18e9ee042b3e204bc5992612e990d3b3a0fb1f9627b1a3bae11e9fa20dffc96e136bd734a2f3cf92a0d05bedd42cfe/lib/language_pack/helpers/rake_runner.rb:102:in `load_rake_tasks!': Could not detect rake tasks (LanguagePack::Helpers::RakeRunner::CannotLoadRakefileError)  remote: ensure you can run `$ bundle exec rake -P` against your app  remote: and using the production group of your Gemfile.  remote: This is an old, deprecated version of the Ruby PostgreSQL driver that hasn't  remote: been maintained or supported since early 2008.  remote:   remote: You should install/require 'pg' instead.  remote:   remote: If you need the 'postgres' gem for legacy code that can't be converted, you can  remote: still install it using an explicit version, like so:  remote:   remote:   gem install postgres -v '0.7.9.2008.01.28'  remote:   gem uninstall postgres -v '>0.7.9.2008.01.28'    ...    remote:  !     Push rejected, failed to compile Ruby app.  remote:   remote:  !     Push failed  remote: Verifying deploy...  remote:   remote: !   Push rejected to git_name_repo.  remote:   To https://git.heroku.com/git_name_repo.git   ! [remote rejected] master -> master (pre-receive hook declined)  

More efficient to update or rebuild Rails 2.3.X app?

Posted: 30 Sep 2016 04:32 AM PDT

I have a Rails 2.3.X app. I plan to hire a developer to either update the site to current Rails standards or rebuild the site. In general, is there a way to evaluate whether it's more cost-effective to update versus rebuild? My preference is to update.

Safe way to allow Rails code review?

Posted: 30 Sep 2016 04:29 AM PDT

I have someone interested in purchasing my Rails app (2.3.18). It requires updating (obviously), and now it's a question of the cost of updating versus rebuilding from scratch.

If the buyer wants to have third-party developer review the code to determine this effort and estimate costs, is there a way to allow this developer access without losing control or granting unsafe access?

How to filter the range using Axlsx with filters on some columns

Posted: 30 Sep 2016 04:07 AM PDT

I am generating a spreadsheet using Axlsx gem. My data table has more than 10 columns but I have to add filters to first 5 columns only.

sheet.auto_filter = "A5:E20"  

The problem is that these filters works only on 5 columns not on the whole table which has 10 columns. So for example when I sort the table by the first column only cells in these first 5 columns are sorted and the other cells are not touched. Is there a way to have filters on some columns but makes filtering working on the whole table?

amount withdrawal from website seller paypal account to any website user paypal account using rails

Posted: 30 Sep 2016 06:32 AM PDT

I have tried to do the payout in sandbox mode which resulted in a declined status as the account is unverified.

I have also tried Adaptive payments, it's working but the problem is that it is redirecting for the session followed by a confirmation to transfer to the account.

How to Embed a PowerBI Tile in a Rails app? (and apply filter to it)

Posted: 30 Sep 2016 03:35 AM PDT

I'm struggling with this since a week... I have tried so many things, read so many documentations (walkthrougsh), I can't find any solutions and I have lost the clarity. I really need your help.

  • I have created a simple Rails app.

  • I have a Power BI account and a Azure account.

  • I'm using an example set of data on PowerBI (Retail Analysis Sample).

I want my users to signin on my app (through devise), then access to some pages and see embedded PowerBI Tiles (or report, or dashboard maybe). Then I want them to be able to filter the results. A client-side example is https://microsoft.github.io/PowerBI-JavaScript/demo/filters.html. I want to be able to do the same.

I'm lost with all the client id, secret, ressource uri, ressource url, ... What solution/walkthrough must I use?


Thank you so much for your time

Fro

Impossible to store data in base from a form

Posted: 30 Sep 2016 03:24 AM PDT

Im trying to store data in rails, but I simply can't, everytime I push with submit button, the values on base are null and the method save try to store data before I push button submit, here is my code :

images_controller.rb:

class ImagesController < ApplicationController    layout 'home2'    #before_action :image    def new      @image = Image.new    end      def create      @image = Image.new(image_params)        if @image.save        flash[:success] = "Your creation has been uploaded"        #redirect_to "/showcase"      else        flash[:error] = "Your creation has not been uploaded"        render :new      end    end        private        def image_params        params.permit(:title, :description, :nickname, :creation)      end  end  

my view create.html.erb:

<h2 align="center">Post your own creation right here !</h2>  <br>  <div align="center">    <%= link_to 'Back', '/showcase', :class => "buttonShow" %>  </div>    <%= simple_form_for @image, url: "/showcase/post", html: { multipart: true } do |f| %>    <%= f.input :title, :required => true %>    <%= f.input :description, :required => true %>    <%= f.input :nickname, :required => true %>    <div align="center">    <%= f.file_field :creation, :required => true %>      <%= f.button :submit, "Post !", :class => "buttonShow1"  %>    </div>  <% end %>  

route.rb :

Rails.application.routes.draw do    resources "images", only: [:create, :new]    resources "contacts", only: [:new, :create]    get 'contacts/contact'      #get 'images/crea'    #get 'images/post'      get 'auth/auth'      root "auth#auth"    #get 'contact' => 'contacts#contact'    get 'showcase/post' => 'images#create'    #post 'showcase/post' => 'images#create'    get 'showcase' => 'images#new'    post 'showcase/post' => 'images#create'    patch 'showcase/post' => 'images#new'    get 'images' => 'images#new'    #get 'images/new' => 'showcase'    #resources "contacts", only: [:new, :create]    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html  end  

model : image.rb

class Image < ApplicationRecord      has_attached_file :creation,      :styles => {        :large => "1000x1000>",        :medium => "500x500>",        :thumb => "300x300#"      }    #validates :creation, :attachment_presence => true    validates_attachment_content_type :creation, content_type: /\Aimage\/.*\z/    # has_attached_file :image_filename    # validates_attachment :image_filename, :presence => true    #validates_attachment_file_name :image, :matches => [/png\Z/, /jpe?g\Z/]    #attribute :title, :presence => true    # attribute :description, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i    # attribute :nickname, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i  end  

schema.rb

ActiveRecord::Schema.define(version: 20160930075924) do      create_table "contacts", force: :cascade do |t|      t.string   "name"      t.string   "email"      t.string   "message"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "images", force: :cascade do |t|      t.string   "title"      t.string   "description"      t.string   "nickname"      t.datetime "created_at",            null: false      t.datetime "updated_at",            null: false      t.string   "creation_file_name"      t.string   "creation_content_type"      t.integer  "creation_file_size"      t.datetime "creation_updated_at"    end    end  

I simply can't store data with the form in my bases, Ive tried everything.

Thanks in advance for your help.

Supporting two incompatible gem versions for a dependency

Posted: 30 Sep 2016 04:03 AM PDT

I have a gem that I use which currently depends on the google-api-client v 0.8x, I'd like to update the gem to support google-api-client v 0.9x.

The Auth between those two is completely different and incompatible.

Is there a way to know which version of the gem dependency is intalled and act accordingly? So I can add the support for those people who for whatever reason have upgraded the API client whilst continuing to allow people still on the older version to use it.

No comments:

Post a Comment