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.

Thursday, September 29, 2016

Send_file open file in browse instead of download it | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

Send_file open file in browse instead of download it | Fixed issues


Send_file open file in browse instead of download it

Posted: 29 Sep 2016 07:55 AM PDT

please tell me how it's work, coz i'm don't understand... My simple code

Route

 get 'download' =>'pages#download'  

My actinon

def download    send_file "#{Rails.root}/public/downloads/robots.zip", :type=>"application/zip"  

and download link

<%= link_to "download", download_path%>  

So, when i'm clicking on the link I get this http://joxi.ru/GrqvQ3xHlbaYmz it's seems like browser try to show zip file content... But when I open my action from browser (or refresh page) it's work fine

Why it's don't work when I click on the link generated by link_to (it open http://joxi.ru/GrqvQ3xHlbaYmz ?

How to learn Ruby on Rails *Source Code*? [on hold]

Posted: 29 Sep 2016 07:50 AM PDT

There are many tutorial on the web teach about how to use Ruby on Rails
But I can't find any tutorial about how Ruby on Rails work under the hood

I really want know how Ruby on Rails work under the hood,
someday may even contribute code into Ruby on Rails
(for now seem like there are long way to go)

Where should I start?

Learn about what is gem? and then what is rack? and then what?
Any Suggestion? Thanks

Am I asking the wrong question?
or I am posting a question at a wrong place?
4 downvote within 1 minute? really??

Rails routes resources - add extra param on all routes

Posted: 29 Sep 2016 07:49 AM PDT

I wanna generate some routes for my scaffold, but in some way that all of then looks something like:

/companys/:type  /companys/:type/new  /companys/:type/:id/edit  

so I can catch that "type" param on my controllers. I don't wanna do it manually... Is there some way to easily add that :type param? Thanks!

Retrieving attributes of associated object Rails

Posted: 29 Sep 2016 07:39 AM PDT

I have a post that has many comments. Comments have a body and a title

 => #<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, author: "jack", body: "how do you like dem apples?", post_id: 1, created_at: "2016-09-29 02:11:00", updated_at: "2016-09-29 02:11:00">]>   2.3.0 :005 > Post.first.comments    Post Load (0.5ms)  SELECT  "posts".* FROM "posts"  ORDER BY "posts"."id" ASC LIMIT 1    Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?  [["post_id", 1]]   => #<ActiveRecord::Associations::CollectionProxy [#<Comment id: 1, author: "jack", body: "how do you like dem apples?", post_id: 1, created_at: "2016-09-29 02:11:00", updated_at: "2016-09-29 02:11:00">]>   2.3.0 :006 > Post.first.comments.body    NoMethodError:   Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?  [["post_id", 1]]  undefined method `body' for #<Comment::ActiveRecord_Associations_CollectionProxy:0x007f9bef0a33a8>  

In the code above you can see that I try to get the body attribute from the post that has a comment, but I get a no method exception. How do I retrieve the associated objects data in these types of situations?

SQLite3::BusyException: database is locked: INSERT INTO

Posted: 29 Sep 2016 07:54 AM PDT

When I run this piece of code with a task, it works

task :importGss => :environment do      Gss.delete_all      file = Rails.root + "app/assets/CSVs/gss.csv"      csv_text = File.read(file)      puts csv_text.size      csv = CSV.parse(csv_text, :col_sep => ';', :headers => true)      csv.each do |row|      Gss.create!(row.to_hash)  end    

When I run it with a MVC, I have the following message :

ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked:

I have put the above code in a function in the Gss model. The import is launched from the browser with a GET that is routed to the controller that calls the model import function When the import is finished, the complete list of record should then be returned to the view. the csv file has 4k rows. The process of importing takes time and it seems that after precisely 60 seconds the GET is resend. Can someone explain me how to avoid this resending that crashes the import ?

Get list of all regitered connections

Posted: 29 Sep 2016 07:28 AM PDT

http://stackoverflow.com/a/36230416/5381547

http://stackoverflow.com/a/32945949/5381547

Those answers don't help me.

I want to get list of all registered connections to my ActionCable. I tried

Redis.new.pubsub("channels", "action_cable/*")

and

ActionCable.server.connections.length,

but they both return []. So for now I'm using something like

def connect    self.uuid = SecureRandom.uuid      players_online = REDIS.get('players_online') || 0    players_online = players_online.to_i    players_online += 1    REDIS.set('players_online', players_online)  end    def disconnect    players_online = REDIS.get('players_online').to_i    players_online -= 1    REDIS.set('players_online', players_online)  end  

But I know that this is a totaly not Rails-way. Is there any possibility to get a list of all registered connections?

keep changed style by javascript after showing flash error message in ruby on rails

Posted: 29 Sep 2016 07:27 AM PDT

I have a div part in my HTML(erb), whose display is "none" at first. Then I change its style to "block" detecting the input values of datetimepicker.

I have succeeded to change the style, but the style reverses to "none" if the form gets flash error message shown after validation.

Is there any way to keep the style changed even after error message shows up.

Here is my code of javascript.

  $('.datetimepicker').on('dp.change', function(e) {       var x = document.getElementById("from").value;      var y = document.getElementById("to").value;      var date_y = Date.parse(y);      var date_x_day = Date.parse(x) + (1 * 86400000);        if (date_y > date_x_day) {        $('#hotel').fadeIn(500);       } else {        $('#hotel').fadeOut(500);      }    });  

I tried to put the line below after "$('#hotel').fadeIn(500); " but it doesn't work.

document.getElementById('hotel').style.display="block";  

Could anyone tells me the best way??

Impossible to display the image uploaded with paperclip

Posted: 29 Sep 2016 07:54 AM PDT

I got a problem with paperclip, I just can't display the image who has been uploaded, here is my code :

images_controller.rb :

class ImagesController < ApplicationController    layout 'home2'    def new      @image = Image.new    end      def create      @image = Image.new(params[:images])      end      def post_params        params.require(:image).permit(:title, :description, :nickname, :creation)      end  end  

My migration generate with paperclip

class AddAttachmentCreationToImages < ActiveRecord::Migration    def self.up      change_table :images do |t|        t.attachment :creation      end    end      def self.down      remove_attachment :images, :creation    end  end  

my model image.rb:

class Image < ApplicationRecord    has_attached_file :creation,      :styles => {        :large => "1000x1000>",        :medium => "500x500>",        :thumb => "300x300#"      }    validates_attachment_content_type :creation, content_type: /\Aimage\/.*\z/  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 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 %>      <%= image_tag @image.creation.url(:thumb) %>  

and my routes.rb

Rails.application.routes.draw do    resources "images", only: [:new, :create]    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'    get 'showcase' => '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  

I don't know why I can't upload any files, the display look like this : http://hpics.li/131d722

I just tried with a new project and it work but with this code , it doesnt work, I think the path of the image is wrong maybe, but im not sure and I don't know how to fix it.

Thanks in advance for your help.

Display filters prams when selected

Posted: 29 Sep 2016 07:23 AM PDT

I m making an rails app. I have search function with params and i want to display in my view filters params when they are slected but i dont know how i can do that.

Image is better than words so i want this http://img4.hostingpics.net/thumbs/mini_398032filterparams.jpg or image 2

camping_controller.rb

  def resultnohome            if params[:query].blank?              redirect_to action: :index and return            else              @campings = Camping.searchi(params[:query], params[:handicap], params[:animaux])            end    end  

resultnohome.html.erb

<%= render 'searchfilter', camping: @camping %>  

_searchfilter.html.erb

<%= form_tag(resultnohome_path, method: :get) %>    <%= text_field_tag :query, params[:query], class:"SearchFilter", placeholder:"Ex : Vendée, Corse..." %>    <li><p><span class="IcoHandi" aria-hidden="true"></span> Accès handicapé : <%= check_box_tag :handicap, "oui", !!params[:handicap], :class => "handicap" %></p></li>    <li><p><span class="IcoPets" aria-hidden="true"></span> Animaux acceptés : <%= check_box_tag :animaux, "oui", !!params[:animaux], :class => "animaux" %></p></li>    ...    <%= submit_tag "Appliquer les filtres", class:"btn btn-danger2", name: nil %>  <% end %>  

So my question is : How i can do that ? Thanks for your help !

Rails: belongs_to twice on same field

Posted: 29 Sep 2016 07:23 AM PDT

Please, anyone know, can I declare relation belongs_to twice to same field?

For example:

class Notice < ApplicationRecord    belongs_to :avia, foreign_key: 'ticket_id', class_name: 'AviaTicket'    belongs_to :bus, foreign_key: 'ticket_id', class_name: 'BusTicket'  end  

In this way, I have use ticket_id twice for different models. And on belongs_to side its doen't work, but on otherside(AviaTicket, BusTicket) works fine.

Rails Sunspot - not working search

Posted: 29 Sep 2016 07:06 AM PDT

I added a sunspot gem into my rails app and my model looks like this:

class Lab < ApplicationRecord      searchable do          text :name      end  end  

I run the commands as the docs said (with reindex command included).

After doing:

@search = Lab.search do       fulltext "laboratory"  end  @results = search.results  

the @results is an empty array, and I do have a record with name containing "laboratory".

I do not see any error, so what did I do wrong?

Bind error message on another attribute

Posted: 29 Sep 2016 07:08 AM PDT

I have the following validation rule in a model

validates :csv_fingerprint, uniqueness: { message: "CSV was already uploaded." }  

In the form view (simple_form), the following code generates the file upload field:

= f.input :csv, as: :file  

The validation works, but the error message is not shown at the upload field. I think, the reason is, that the validation is for :csv_fingerprint and the form field is :csv.

How can I tell the validation rule, that the message should be displayed at the :csv field?

Rails - two forms in one (ShopifyAPI)

Posted: 29 Sep 2016 07:33 AM PDT

Part of the app i'm developing involves a form which has to create a product on the users shopify store and also create a row in my own database for an identical product (with a few extra bits of information).

Where i'm struggling is with the form itself, i can do this with a html based form, but i can't get a single ruby form to do both jobs. A shortened version of my controller create code is as follows;

def create      @item = Item.new      @item.item_title = params[:item_title]      @item.item_profit = params[:item_profit]      @new_product = ShopifyAPI::Product.new      @new_product.title = params[:item_title]      @new_product.save      @item.save  end  

So as you can see i'm using the same params to set values for both the shopify product and the product in my own db. The HTML form looks like this:

<form action="/items/submit" >    <input type="text" name="item_title">    <br>    <input type="text" name="item_profit">    <br>    <br>    <input type="submit"/>  </form>  

And it works fine, but how do i convert this into a ruby form that does the same job?

Add a title to my select_tag

Posted: 29 Sep 2016 07:46 AM PDT

I am trying to put a title to my select_tags I would like to have something like Select a user and then all the users appear below... for now I have the name of the first user... I don't want that... Any suggestion? I can't find anything working with my view...

thanks for your help

=form_tag tutos_path, :method => 'get' do           =select_tag :select, options_for_select(User.order('nickname ASC').all.map{|u| u.nickname}, params[:select])          =submit_tag "Select", class:"btn btn-xs btn-default btn-search"  

Ruby on Rails error when validates_uniqueness_of using collection_select

Posted: 29 Sep 2016 06:59 AM PDT

First, sorry for my bad English. I'm still learning.

I have 3 tables in my DB:

Problem

  • has_many :registers
  • has_many :solutions, through : :registers

Solution

  • has_many :problems
  • has_many :problems, through : :registers

Register

  • belongs_to: problem
  • belongs_to :solution

The system is working well. I am able to insert new data in all of the 3 tables.

In the views for the table/model Register, to select problems and solutions, I make use of collection_select, like this:

= collection_select( :register, :problem_id, @problems, :id, :name, {}, { :multiple => false })  

The problem only appears when I try to add this validation to Register:

validates_uniqueness_of :student_id , scope: :course_id  

Then I get:

> undefined method `map' for nil:NilClass   > = collection_select( :register, :problem_id, @problems, :id, :name, {}, { :multiple => false })  

And I dont know why.

So, I tried to do the validation by the controller:

def create    @register = Register.new(register_params)    problem_id = @register.problem_id     solution_id = @register.solution_id    if Register.exists?(['problem_id LIKE ? AND solution_id LIKE ?', problem_id, solution_id ])      render 'new'    else      @register.save      respond_with(@register)    end  end  

But the error remains.

I believe that the cause is the collection_select, but I don't know how to solve it.

Saying one more time, I am able to persist date in all the 3 DB tables. But when I try to avoid duplication, the error appears.

Confirm popup not working

Posted: 29 Sep 2016 06:20 AM PDT

I have a problem as the confirm popup is not showing, when i use my delete button. The deleting works fine, i just dont get the "are you sure" popup first.

I have tried different variantions of this code, without any luck. I think i have the confirm part correct, but perhaps not. What am i missing here?

<%= link_to t('common.delete'), car_path(@current_work_context, car), :method => :delete, :confirm => t('common.are_you_sure'), :class => "btn btn-danger btn-xs" if car.deletable? %>  

Ajax fires up multiple times unless page is Reloaded, Rails 4 and Bootstrap

Posted: 29 Sep 2016 06:10 AM PDT

I have simple app with index and show pages. Pretty simple code and etc. Simple registration that is handled with Devise gem.

In index page I have such Bootstrap modal for registration:

     <div class="modal fade" id="register" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">                          <div class="modal-dialog log-modal">                              <div class="modal-content">                            <div class="user-registration-content">                                <div class="modal-header clearfix">                                  <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>                                  <h4 class="modal-title pull-left"><%= t('user_creation') %> <!--Lietotāja izveide --></h4>                                    <%= link_to '#',:class=>"pull-right",:id=>"login-path-link" do %>                                                   <span><%= t('already_registered') %> <!--Jau esi reģistrēts --></span>                                      <%end%>                              </div>                                <div class="modal-body">                                  <span><%= t('please_fill_form') %></span>                                    <%= form_for(@user, :html => {:id=>"sign_up_user" ,:class=>"registration-form-modalc","data-parsley-validate" => true},remote: true, format: :json,as: @user, url: registration_path(@user)) do |f| %>                                        <div class="form-group">                                                                               <%= f.text_field :name,:class=> "user-input form-control", :id=>"user-name",autofocus: true ,:placeholder=> t('username_2'),:required => true,:'data-parsley-minlength'=>"3"%>                                                                          </div>                                        <div class="form-group">                                                                    <%= f.password_field :password,:id=>"passwordis",:class=> "user-input form-control", autocomplete: "off" ,:placeholder=> t('new_password'),:required => true,:'data-parsley-minlength'=>"8" %>                                                                           </div>                                        <div class="form-group">                                          <%= f.password_field :password_confirmation, :id=>"password-again",:class=> "user-input form-control", autocomplete: "off" ,:'data-parsley-equalto'=>"input#passwordis",:placeholder=> t('new_password_2'),:required => true,:'data-parsley-minlength'=>"8"%>                                          <%= f.hidden_field :role, :value => "user"%>                                          <%= f.hidden_field :country_id, :value => @location.id%>                                                                                              </div>                                        <div class="form-group">                                         <%= f.email_field :email ,:class=>"user-input form-control" ,:'data-validatess' => '/blocked/checkemail',:id=>"emailito",:placeholder=> t('email'),:required => true%>                                            <h3 id="email-taken-message" style="display:none;margin-left:140px;color:red;padding-top:7px;"> <%= t('email_not_available') %> </h3>                                                                                                                                                      </div>                                        <%= f.hidden_field :humanizer_question_id %>                               <div class="question-content" style="position:relative;top:1px;">                                  <span class="question"><%= t('question') %>:</span>                                  <span class="answer"  >                                   <%= f.label :humanizer_answer, @user.humanizer_question %>                                  </span>                                  <div class="form-group" style="margin-bottom:21px;">                                 <span class="question" style="margin-top:8px;"><%= t('answer') %>: *</span>                                                                   <%= f.text_field :humanizer_answer ,:class=> "form-control",:required => true, :id=>"answer"%>                                </div>                                                                     </div>                            <%= f.submit t('confirm'),:class=> "blue-button btn btn-default"%>                                    <div class="squared">                                        <%= f.check_box :terms_of_service,:id=>"accept",:required => true,:type=> "input"%>                                      <!--<input type="checkbox" value="" id="accept" name="check" /> -->                                      <label style="left: 0px;"for="accept"><span><%= t('read_and_agree') %> <!--Izlasīju un piekrītu  -->                                          <%= link_to t('rules_2'),help_path, :target=>'_blank' %>                                      </span>                                        </label>                                      </div>                                    <div class="squared">                                        <%= f.check_box :not_a_robot,:id=>"user-status",:required => true, :type=> "input"%>                                      <label style="left: 0px;"for="user-status"><span><%= t('not_robot_confirm') %></span></label>                                    </div>                                      <div class="squared">                                   <%= f.check_box :im_old,:id=>"user-age",:required => true, :type=> "input"%>                                        <label style="left: 0px;"for="user-age"><span><%= t('already_adult') %></span>                                        </label>                                   </div>                                </div>    <%end%>    </div>                   </div>            </div>      </div>  

At the end of the Application_layout file:

 <%= javascript_include_tag "application" %>          <script src="/assets/lightbox.js"></script>      <script src="/assets/bootstrap.min.js"></script>      <%= javascript_include_tag "co.js" %>        <script src="/assets/scripts.js"></script>    

Registration process is handled with remote => true.

script.js:

$(document).ready(function() {    return $("form#sign_up_user").on("ajax:success", function(e, data, status, xhr) {                   $(".user-registration-content").hide();               $(".registration-sent").show();        }).on("ajax:error", function(e, xhr, status, error) {          alert("Error user registration");      });  });  

Application.js file:

//= require jquery  //= require jquery_ujs  //= require jquery.remotipart  //= require turbolinks  //= require parsley  //= require_tree.  

Problem: Unless I refresh page before triggering modal and filling in form, submitting form triggers 2 identical requests. If I visit show page and then come back to index page to register form submitting triggers 4 identical requests.

Basically, each time user visits show page number of requests increases by 2. At the end requests can go up to 10 and more. After reloading page everything is back to normal.

The same problem occurs when I click on page logo that sends to root_path that is basically the same index page. And the cycle continues.

What I tried:

1) Deleted every other script from scripts.js file except the script for handling registration process (see above for script)

2) Changed all click elements to .one('click', function()

3) Removed every other Bootstrap modal from my page so the conflict possibility could be excluded.

4) Double checked page source for index and show page to check if script.js file is called just once.

5) I have cleared tmp/assets folder.

6) Problem happens on all browsers.

Note: This problem occurs on every ajax request. In my app I have lot of modals with ajax submitting and every of them have the same problem unless I reload page each time.

I have run out of options to try.

Thank you in advance for any help.

Rails 5 - limit selection of associated object

Posted: 29 Sep 2016 07:18 AM PDT

In my app that I am building to learn RoR, I have Annotation (for documents of a document type) with tags (much like posts and comments). When adding a tag to an annotation, I want to limited the possible types of the tag to those tag types that have the same document type as the document type of the annotation.

To reduce the list of tag types I already use a scope to get active tag types. Like so:

<%= f.association :documenttype, :collection => Documenttype.active.order(:name) %>  

with this scope

scope :active, -> { where(active: true) }  

How can I extend it for matching document types? If with a scope, how; if not, what approach should I take then?

Rails - NoMethodError undefined method `>=' for nil:NilClass

Posted: 29 Sep 2016 06:33 AM PDT

I'm getting the above error in my model. Here's the model code -

Booking.rb

    class Booking < ActiveRecord::Base        belongs_to :event      belongs_to :user        validates :quantity, presence: true, numericality: { greater_than: 0 }      validates :total_amount, presence: true, numericality: { greater_than: 0 }      validates :event, presence: true, numericality: {greater_than_or_equal_to: 0 }        before_validation :set_default_values_to_greater_than_or_equal_to_zero        def set_default_values_to_greater_than_or_equal_to_zero          self.quantity >= 1          self.total_amount >= 0            self.event.price >= 1    unless self.event.is_free      end        def reserve(stripe_token)          # Don't process this booking if it isn't valid          self.valid?            # We can always set this, even for free events because their price will be 0.          #self.total_amount = booking.quantity * event.price                    # Free events don't need to do anything special                  if event.is_free?                  save!                    # Paid events should charge the customer's card                  else                        begin                          self.total_amount = event.price * self.quantity                          charge = Stripe::Charge.create(                              amount: total_amount,                              currency: "gbp",                              source: stripe_token,                               description: "Booking created for amount #{total_amount}")                          self.stripe_charge_id = charge.id                          save!                      rescue Stripe::CardError => e                      errors.add(:base, e.message)                      false                  end              end