Tuesday, August 16, 2016

Migrating Data from Remote MySQL server to Rails App | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

Migrating Data from Remote MySQL server to Rails App | Fixed issues


Migrating Data from Remote MySQL server to Rails App

Posted: 16 Aug 2016 07:45 AM PDT

This is a follow up question to this question from 5 years ago.

I'm trying to create an SSH tunnel in Ruby and then connect to a remote MySQL database. I'm doing this because I need to move some legacy data from an older version of my app, so I don't need ActiveRecord, migrations, etc.

I'm using the NetSSHGateway gem and the MySQL2 gem.

Here's my Ruby code (run in rails console):

gateway = Net::SSH::Gateway.new('old_remote_server.com','server_username')  port = gateway.open('127.0.0.1', 3306, 3307)  client = Mysql2::Client.new(    host: "127.0.0.1",     username: 'database_username',     password: 'database_password',     database: 'database_name',     port: port  )  

After the last line, the console hangs for about 2 minutes, and then gives me the error:

Mysql2::Error: Lost connection to MySQL server at 'reading initial communication packet', system error: 0  

I am able to SSH into the remote server, and execute MySQL commands that way, so I'm not sure what the issue is here.

Optional argument/param in ruby

Posted: 16 Aug 2016 07:45 AM PDT

I have method to which I want to pass an optional argument. By default I want to set that argument as nil. Here is the way I am doing it:

def my_function(arg1, arg2: nil)    # Do something  end  

I call the function as my_function(2, 5). I am getting an error which says: "wrong number of arguments (given 2, expected 1)"

Am I doing something wrong here? I wish to pass a value for arg2 during some calls and want it to be nil otherwise. So when I don't pass a value for arg2, my function call looks like my_function(2).

ActiveRecord scope with offset / limit

Posted: 16 Aug 2016 07:35 AM PDT

I ve got two scopes in my active record model, scope1 and scope2. For the new functionality I need result of the union query of these two scopes, so I have a method like this :

def new_functionality    union_sql = [      scope1.select('id').to_sql,      scope2.select('id').to_sql    ].join(' UNION ')      where("id IN ( ${union_sql.squish } )")  end  

This works well when displaying the whole data set, but since the performance is becoming issue I need to user offset/limit to control it. And since the data is driven by the inner query (union of scope1 and scope2), I need to apply limit on scope1 and scope2.

If I apply the offset/limit on the new_functionality the whole data set will be evaluated and only subset returned based on the offset/limit values.

How can I create a method that will enable me to set limit/offset values on the inner scopes (scope 1 and scope2)? Is my approach wrong in this case?

Pass Parameters from Grape::API to Serializer

Posted: 16 Aug 2016 07:35 AM PDT

I am getting a parameter e.g: member_id in Grape::API like

   desc 'Return Events'           params do               requires :member_id, type: Integer, desc: 'Member'           end           get 'all' do                #some code           end       end  

and I want to pass it to ActiveModel::Serializer so that I can perform some functionality.

Is there any way that I can pass it to ActiveModel::Serializer?

Capybara drivers for diffrent layouts

Posted: 16 Aug 2016 07:21 AM PDT

I have two drivers

  • Desktop Version
  • Mobile version

Mobile:

Capybara.register_driver :selenium do |app|    args = []    args << "-user-agent='Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'"    Capybara::Selenium::Driver.new(app, :browser => :chrome, :args => args)    end  

Desktop:

Capybara.register_driver :selenium do |app|    Capybara::Selenium::Driver.new(app, :browser => :chrome)  end  

and currently i add it for each test and it's a bit inconvenient.

I want to set it up in my spec_helper,but how i can do it?

The result should look like this:

if folder.mobile?   use mobile driver   else    desktop driver  end   

Rails nested_form inside nested_form

Posted: 16 Aug 2016 07:45 AM PDT

I have the following models and relations:

Rate fields    t.string :type    t.string :name    class Rate < ActiveRecord::Base    has_many :category_rate_requests  end    CategoryRateRequests fields    t.date :date_from    t.date :date_to    class CategoryRateRequests < ActiveRecord::Base    belongs_to :rate    has_many :category_rates  end    CategoryRate     t.integer :room_category_id    t.integer :new_rate_id    t.integer :category_rate_request_id    t.integer :amount    class CategoryRate < ActiveRecord::Base    belongs_to :rate    belongs_to :category_rate_request    belongs_to :room_category  end  

And I'm trying to have a nested_form inside a nested_form

= nested_form_for @rate do |f|    = label_tag :name, t('rates.new.name'), class: 'grey h2'    = f.text_field(:name, required: true, class: 'form-input form-control full-width-input')    = f.fields_for :category_rate_request do |request|      = request.text_field(:date_from,  class: 'date-input form-control start-date-input', type: 'text', 'data-provide': 'datepicker', placeholder: t('common.date_from'))      = request.text_field(:date_to, class: 'date-input form-control end-date-input', type: 'text', 'data-provide': 'datepicker', placeholder: t('common.date_to'))      = request.fields_for :category_rate, do |u|        = u.number_field(:price, class: "form-control", placeholder:  placeholder)  

Overall this is the format. It has more things, but to not include too much unnecesary information I omitted some fields of the form.

But I get the following error

Completed 500 Internal Server Error in 690ms (ActiveRecord: 6.1ms)

SyntaxError - syntax error, unexpected keyword_do_block ; _slim_controls2 = request.fields_for :new_category_rate, do |u|; ^ /project/app/views/new_rates/_category_rate_requests.html.slim:61: syntax error, unexpected keyword_ensure, expecting end-of-input:

That line marked in red is:

= request.fields_for :new_category_rate, do |u|

Is there any way I can have the attributes of all three models in one form? In the Rate form more precisely.

How to keep specific text fields hidden until a user selects an action that complies with that specific field(s)

Posted: 16 Aug 2016 07:34 AM PDT

I spent time learning Rails and now I'm working on a demo project.The first thing I want the user to do, is to select whether or not they need immediate care on a care request _form. If the user selects "false" then the user will be asked to select a time and date from the next two hidden lines of code, passing in my start_time and start_date. If the user selects "true", I want to use Time.now to get the current time and current date for my start_time and start_date fields when the user clicks the submit button on the request _form. My question is What is the proper way to keep the last two fields hidden until a user selects "false"? requests_form.html.erb

<div class="row">      <div class="form-group">       <%= f.check_box :immediate_care,{:checked => "checked"} %> Patient needs immediate care.      </div   </div>       <div class="row">     <div class="form-group">         <label>Choose your start date.</label>         <%= f.text_field :start_day, placeholder: "MM/DD/YY", class: "form control" %>         </div>   </div>    <div class="row">     <div class="form-group">        <label>Choose your start time.</label>        <%= f.text_field :start_time, placeholder: "08:00 AM", class: " form-control" %>        </div>  </div>        

Stripe Tests works fine in development but fails in tests

Posted: 16 Aug 2016 07:01 AM PDT

When I try to register a credit card in Swift, it works on development but I cant make a passing test of it. I am unsure how JS loads in Capybara so that may be the problem. It seems that my card token is not getting passed in testing but I cant figure out why...

RSPEC Test

    require 'rails_helper'  require_relative '../support/new_login_form'  require_relative "../support/new_credit_card_form"    feature 'home page' do    let(:sign_in_form) { NewLoginForm.new }      let(:user) { FactoryGirl.create(:user) }      let(:credit_card_form) { NewCreditCardForm.new }      before(:each) do      @article = FactoryGirl.create(:article)      @user1 = User.create(email: 'email@email.com', password: "password")      @article_premium = Article.create(name: "Premium", premium: true, content:" hello")    end      scenario 'welcome message' do      visit('/')      expect(page).to have_content("Hello World!")    end      scenario 'Click Free content' do      visit("/")      click_on(@article.name)      expect(page).to_not have_css('.alert')    end      scenario 'Click Premium content' do      visit("/")      click_on(@article_premium.name)      expect(page).to have_css('.alert')    end      scenario 'Correct sign up' do      sign_in_form.visit_page.fill_in_with.submit      expect(page).to have_content("You have signed up successfully.")    end      scenario 'Wrong sign up' do      sign_in_form.visit_page.fill_in_with(        password: "INCORRECT PASSWORD"      ).submit      expect(page).to have_content("Password confirmation doesn't match Password Email Password")    end      feature "log in" do      before do        sign_in_form.login_as(user)      end        scenario "Sign in" do        expect(page).to have_content("@email.com")      end        feature "Credit Card" do          before do        end          scenario 'Illegal Credit Card' do          credit_card_form.visit_page.fill_in_with(card_number: "4000000000000127").submit          expect(page).to have_css(".alert")        end          scenario "Register Credit Card" do         credit_card_form.visit_page.fill_in_with.submit  #      save_and_open_page         expect(page).to have_content("Cancel Subscription")        end          scenario "Cancel Credit Card" do  #       click_on("Cancel Subscription")  #       expect(page).to have_css(".alert")        end       end      end    end  

Submission Form with JS

<h4>Begin your $5.00 a month subscription</h4>  <form action="/users/charge" method="POST" id="payment-form">    <span class="payment-errors"></span>    <div class="row">      <div class="col-md-6">        <label>Card Number</label>        <input class="form-control" type="text" name="Card Number" size="20" data-stripe="number" placeholder="4242424242424242"/>      </div>    </div>    <br />    <div class="row">      <div class="col-xs-2">        <label>CVC</label>        <input type="text" data-stripe="cvc" class="form-control" name="CVC" placeholder="123">      </div>    </div>    <br />    <div class="row">      <div class="col-xs-2">        <label>Expiration</label>      </div>    </div>    <div class="row">      <div class="col-xs-4">        <label>MM</label>        <input type="text" data-stripe="exp-month" class="form-control" name="MM" placeholder="01">      </div>      <div class="col-xs-4">        <label>YYYY</label>        <input type="text" data-stripe="exp-year" class="form-control" name="YYYY" placeholder="2020">      </div>    </div>      <div class="row">      <div class="col-xs-4">        <br/><button class="btn btn-primary" type="submit">Create Subscription</button>      </div>      <div class="col-xs-4">        <br/>        <%= link_to image_tag("big.png"), "https://stripe.com/" %>      </div>      <div class="col-xs-4">        <br/>        <ul>          <li>Reasons To Subscribe:</li>          <li>More tutorials</li>          <li>Personal Contact with A.J.</li>          <li>Request Your own tutorials!</li>          <li>Open Source Help</li>        </ul>      </div>    </div>      <%= token_tag nil %>  </form>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>    <script src="https://checkout.stripe.com/checkout.js"></script>  <script type="text/javascript" src="https://js.stripe.com/v2/">  <script type="text/javascript" src="https://js.stripe.com/v2/">    $(function(){    <% if Rails.env.production? %>      Stripe.setPublishableKey("<%= ENV['STRIPE_PUBLIC_KEY'] %>");    <% else %>      Stripe.setPublishableKey("<%= ENV['STRIPE_TEST_PUBLIC'] %>");    <% end %>  });    </script>  <script type="text/javascript">    <% if Rails.env.production? %>      Stripe.setPublishableKey("<%= ENV['STRIPE_PUBLIC_KEY'] %>");    <% else %>      Stripe.setPublishableKey("<%= ENV['STRIPE_TEST_PUBLIC'] %>");    <% end %>    function stripeResponseHandler(status, response) {    // Grab the form:    var $form = $('#payment-form');      if (response.error) { // Problem!        // Show the errors on the form:      $form.find('.payment-errors').text(response.error.message);      $form.find('.submit').prop('disabled', false); // Re-enable submission      } else { // Token was created!      // Get the token ID:      var token = response.id;        // Insert the token ID into the form so it gets submitted to the server:      $form.append($('<input type="hidden" name="stripeToken">').val(token));        // Submit the form:      $form.get(0).submit();    }  };    $(function() {    var $form = $('#payment-form');    $form.submit(function(event) {        // Disable the submit button to prevent repeated clicks:        $form.find('.submit').prop('disabled', true);          // Request a token from Stripe:        Stripe.card.createToken($form, stripeResponseHandler);          // Prevent the form from being submitted:        return false;      });  });    </script>  

Users Controller

class UsersController < ApplicationController    before_filter :authenticate_user!    attr_accessor :stripe_card_token      def info      @subscription = current_user.subscription        if @subscription.active        @stripe_customer = Stripe::Customer.retrieve(@subscription.stripe_user_id)        @stripe_subscription = @stripe_customer.subscriptions.first      end    end      def charge      token = params['stripeToken']      begin        customer = Stripe::Customer.create(          source: token,          plan: ENV['STRIPE_PLAN_ID'],          email: current_user.email,          )      rescue        flash[:alert] = "Your card was declined. Please try again."        redirect_to users_info_path        return      end        current_user.subscription.stripe_user_id = customer.id      current_user.subscription.active = true       current_user.subscription.save        redirect_to users_info_path    end      def cancel_subscription      @subscription = current_user.subscription      @stripe_customer = Stripe::Customer.retrieve(@subscription.stripe_user_id)      @stripe_subscription = @stripe_customer.subscriptions.first        @stripe_subscription.delete(at_period_end: true)       current_user.subscription.active = false      current_user.subscription.save        flash[:alert] = "You have canceled your subscription!"        redirect_to users_info_path    end    end  

How do I get only some of the belongs_to model of a has_many relationship?

Posted: 16 Aug 2016 06:57 AM PDT

class Comment < ActiveRecord::Base    has_many :replies  end    class Reply < ActiveRecord::Base    belongs_to :comment  end  

I need to get the comments that only have replies from certain users.

I have this in my Comment model:

scope :with_replies_by_users, ->(*user_ids) {  joins(:replies).where(replies: { user_id: user_ids })  }      @comments = Comment.with_replies_by_users([1,2])  

I think this will return all of the comments that have replies by 1 or 2. But it returns all of the replies for those comments. I need only those replies from 1 or 2.

Creating a Form with Dynamically Expanding Text Boxes

Posted: 16 Aug 2016 07:23 AM PDT

I'm a complete noobie to Rails, HTML, CSS and Javascript.

I'm creating a form and I have two requirements:

1) I want text boxes that expand as the text expands in them (see: http://jsfiddle.net/gLhCk/5/)

2.) I want those text boxes to be part of a form that updates objects in a database upon submission.

I've gotten both these pieces working separately -- I can make a text box that expands but doesn't set values in a database, and I can make a form that DOES update a database but doesn't have text boxes that auto-expand.

The difficulty is in combining these two things -- incorporating that Javascript text box into my form that's updating the database.

This is my form that updates the database (with static text boxes):

<div class="row">    <div class="col-md-6 col-md-offset-3">        <%= form_for(@user) do |f| %>        <div class="row">        <h3> Background </h3>          <div class="row">          <%= f.label :hobbs, 'Hobbies' %>          <%= f.text_field :hobbies, class: 'fcdzfform-control' %>        </div>      </div>     </div>  </div>  

And this is the Javascript code that works for an auto-expanding textbox:

<body>      <textarea id="txtInput"></textarea>  <script src="jquery.autogrow-textarea" type="text/javascript"></script>    <script>      $(#txtInput).autoGrow();  </script>  

Like I said, I'm a complete noobie to all this stuff, but the impression I've gotten from browsing online is that I need to abandon the .erb form altogether and make a pure Javascript form, but I'm still failing to see how to have that Javascript form update the values in my database, like the above .erb form is doing.

And advice / guidance? Thanks!

undefined method 'file_name' for nil:NilClas

Posted: 16 Aug 2016 06:53 AM PDT

I have a rails index page that renders a partial. It was once working but now I am getting an undefined method 'file_name' for nil:NilClass.

The FEA_Ref index page calls a partial to render it's list of references. This partial is shared across three different reference pages. It works for the other two, but not FEA_REF. I even looked inside the rails console to make sure the table still associated with reference_file_id, so I'm not sure what would cause to all of sudden think the reference file was nil

app/views/fea_refs/index.html.erb

<%= render 'referenences', object: @fea_refs %>  

app/views/application/_references.html.erb

<ul>  <%= object.each do |reference| %>  <li><%= reference.reference_file.file_name %></li>  <li><%= reference.reference_file.title %></li>  <li><%= reference.page_number %></li>  <li><%= reference.section %></li>  <ul>  

My FEA_Ref Model

class FeaRef < ActiveRecord :: Base   validates :reference_file presence: true   belongs_to :reference_file  end  

Separating List by day created

Posted: 16 Aug 2016 07:04 AM PDT

Hi I'm creating a site with rails and bootstrap where I have a list group populated with posts. I want to be able to have seperate list groups for each seperate day.

For example at the moment I have:

<ul class="list-group">    <% @posts.each do |post| %>      <li class="list-group-item">User has... <%= post.title%> </h2 class="pull-r"> <span class="pull-right"><%=link_to 'View', post%></span></li>    <%end%>  </ul>  

Which give me:

enter image description here

However I want it to look like:

enter image description here

(though obviously with different posts for each day)

but I'm having trouble, any help would be great.

Heroku error with with amazon s3

Posted: 16 Aug 2016 07:32 AM PDT

For Image uploads on my ruby-on-rails application I use the ruby gem paperclip, which works great locally. When it comes to webhosting on heroku, I want to use amazon s3 to store pictures. But every time I upload an image, I get the message

We're sorry, but something went wrong. If you are the application owner check the logs for more information.

On the web somebody said that I'd have to use a 'aws-sdk' older than v2.0, but unfortunately my console says then

uninitialized constat aws

so that the website does not run on local host anymore but also not on heroku (I get an application error).

So I sticked with 2.3, which is also used on the heroku heorku website.

The AWS information (AWS_ACCESS_KEY_ID, AWS_BUCKET, AWS_REGION, AWS_SECRET_ACCESS_KEY...) and the write/read permission should be correct

The production.rb part looks like this

config.paperclip_defaults = {     storage: :s3,      s3_credentials: {        bucket: ENV.fetch('AWS_BUCKET'),        access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),        secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'),        s3_region: ENV.fetch('AWS_REGION'),      }    }  

The Gemfile

gem 'paperclip', '~> 4.3', '>= 4.3.6'  gem 'aws-sdk', '~> 2.3'  

Anybody an idea what I could do to make it work?

Enums in Ruby and getting string value

Posted: 16 Aug 2016 07:16 AM PDT

I have the following module in one of my rails models:

module Color     RED = 0     BLUE = 1     YELLOW = 2  end  

I store these values in a db as ints by doing Color::RED etc. When I retrieve the values back I want to get the string, ie "red". But I am having trouble converting 0 -> "RED"/"red". What am I missing? Can I do this with the module approach or is there a better way?

Trouble connecting to Action Cable with remote origin

Posted: 16 Aug 2016 06:29 AM PDT

I've setup a websocket on our Rails app, and have been able to connect and receive data on it from the same server.

The way I've done it now is to create a socket like this:

class UsersChannel < ApplicationCable::Channel    def subscribed      stream_from "users_1"    end      def unsubscribed      end  end  

and then I use javascript to open the connection with

new WebSocket('wss://domain.com/cable/users_1');

I then broadcast and send JSON from a page in this format:

ActionCable.server.broadcast "users_1", {        store: {          name: store.name,          address: {            full_address: location.address,            latitude: location.latitude,            longitude: location.longitude          }      }  

When that's triggered I can see in my console that it appears. I've added this channel in JS:

App.cable.subscriptions.create "UsersChannel",    received: (data) ->      console.log data  

Now we're working building an app with React Native and when we add this code to our app:

var ws = new WebSocket('wss://domain.com/cable/users_1');    ws.onmessage = (e) => {    console.log(e.data);  };  

we see that it pings, but receive nothing when we trigger the broadcast. I've also added this to the config file:

  config.action_cable.url = 'wss://domain.com/cable'    config.action_cable.disable_request_forgery_protection = true  

Anybody know why this is happening?

rails find(params[:id]) always returns id of the first element

Posted: 16 Aug 2016 06:37 AM PDT

I am trying to get the id of the user of the entry and return it in the documents show view

documents_controller.rb

def show      @document = Document.find(params[:id])      @entries = @document.entries  # to show all entries of a document      @user = Entry.find(params[:id]).user_id # trying to get id of the user that was selected in the entry (always returns id of the first entry of a document)  end  

documents/show.html.erb

<% @entries.each do |document| %>      <tr>          <% userName = @user%>          <td><%= userName %></td> //always gets same id          <% 

No comments:

Post a Comment