Friday, September 2, 2016

ffmpeg - Ruby on Rails | Fixed issues

ffmpeg - Ruby on Rails | Fixed issues


ffmpeg - Ruby on Rails

Posted: 02 Sep 2016 08:08 AM PDT

Regards community,

I want to use ffmpeg, through my web browser.

I would like to do with Ruby - RoR, I understand that these gems can help me:

https://rubygems.org/gems/streamio-ffmpeg

https://rubygems.org/gems/ffmpeg_progress

I have experience with ffmpeg, but with Ruby-RoR I'm a beginner.

Can someone give me an example or guide?

Thank you a lot

can't stop hidden iframes from looping/loading

Posted: 02 Sep 2016 07:56 AM PDT

I can't seem to make these iframes stop looping/loading endlessly multiple times. I just need to to run the url once on the logout route. In the network tab is seems like it keeps running these urls in the iframes over and over. I'm I missing something?

html view

<div id="header">    <div class='logo-container'>      <img class="logo" src="https://s3.amazonaws.com/the/images/logo-with-text.png" alt="The Logo" title=''>      <img class="logo" src="https://s3.amazonaws.com/the/images/logo-white-bg.png" alt="The Logo" title=''>      <img class="logo" src="https://s3.amazonaws.com/the/images/logo_300x100.png" alt="The Logo" title=''>    </div>    <% if @authenticated %>      <a href='/logout'>Logout</a>    <% else %>      <a href='/login'>Login</a>    <% end %>  </div>    <% if @logout_app_urls %>    <% if SETTINGS[:country] == 'US' %>      <iframe src="<%= SETTINGS[:logout_app_urls][:us][:1] %>" hidden="hidden"></iframe>      <iframe src="<%= SETTINGS[:logout_app_urls][:us][:2] %>" hidden="hidden"></iframe>    <% else %>      <iframe src="<%= SETTINGS[:logout_app_urls][:uk][:3] %>" hidden="hidden"></iframe>      <iframe src="<%= SETTINGS[:logout_app_urls][:uk][:4] %>" hidden="hidden"></iframe>      <iframe src="<%= SETTINGS[:logout_app_urls][:uk][:5] %>" hidden="hidden"></iframe>      <iframe src="<%= SETTINGS[:logout_app_urls][:uk][:6] %>" hidden="hidden"></iframe>    <% end %>  <% end %>    <%= yield %>  <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js"></script>  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>  <script src="//cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0/jquery.qtip.min.js"></script>  <script src="<%= escape_html @uri_path %>/themes/the_list/js/test.js"></script>  

logout route (rails)

# 2.3.1  get "#{uri_path}/logout" do    CASServer::Utils::log_controller_action(self.class, params, request)      # The behaviour here is somewhat non-standard. Rather than showing just a blank    # "logout" page, we take the user back to the login page with a "you have been logged out"    # message, allowing for an opportunity to immediately log back in. This makes it    # easier for the user to log out and log in as someone else.    @service = clean_service_url(params['service'] || params['destination'])    @continue_url = params['url']      @gateway = params['gateway'] == 'true' || params['gateway'] == '1'      @test_saml_enabled    = @@config[:test_saml]["enabled"]    @test2_saml_enabled   = @@config[:test2_saml]["enabled"]    @social_login_enabled = @@config[:social_login_enabled]    @test3_providers      = @@config[:test3_providers]    @logout_app_urls      = @@config[:logout_app_urls]      tgt = CASServer::Model::TicketGrantingTicket.find_by_ticket(request.cookies['tgt'])      response.delete_cookie 'tgt'      if tgt      logout_user tgt        $LOG.info("User '#{tgt.username}' logged out.")    else      $LOG.warn("User tried to log out without a valid ticket-granting ticket.")    end      @message = {:type => 'confirmation', :message => t.notice.success_logged_out}      @message[:message] += t.notice.click_to_continue if @continue_url      @lt = generate_login_ticket      if @gateway && @service      redirect @service, 303    elsif @continue_url      render @template_engine, :logout    else      render @template_engine, :login    end  end  

Rails 5 fixture returning nil

Posted: 02 Sep 2016 07:44 AM PDT

Overall Description of Problem:

My fixture for my WeightClass model is returning nil during testing. However, I know the fixtures are valid because when I run rails db:fixtures:load RAILS_ENV=test, all of my fixtures are successfully loaded into my test database.

On a side note, if anybody could point me to the Rails source code that deals with how the weight_classes method (and other methods that turn fixtures into model classes) works in a test, it would be greatly appreciated.


Relevant Files

I have a model for weight classes as seen below (app/models/weight_class.rb):

class WeightClass < ApplicationRecord    validates :name,        presence: true, length: { maximum: 15 }    validates :name_abbr,   presence: true, length: { maximum: 3  }    validates :gender,      presence: true, length: { maximum: 1  }    validates :lower_bound, numericality: { greater_than: 0 }, allow_nil: true    validates :upper_bound, numericality: { greater_than: 0 }, allow_nil: true      validates_with LowerOrUpperBoundRequiredValidator    validates_with RangeValidator, if: :lower_and_upper_bound_present?      private      def lower_and_upper_bound_present?        self.lower_bound and self.upper_bound      end  end  

And it's migration here:

class CreateWeightClasses < ActiveRecord::Migration[5.0]    def change      create_table :weight_classes do |t|        t.string :name, limit: 15, null: false        t.string :name_abbr, limit: 3, null: false        t.string :gender, limit: 1, null: false        t.decimal :lower_bound, precision: 5, scale: 2        t.decimal :upper_bound, precision: 5, scale: 2          t.timestamps      end    end  end  

The fixture in question here (test/fixtures/weight_classes.yml):

middleweight_men:    name: Middleweight    name_abbr: MW    gender: m    lower_bound: 73    upper_bound: 87  

The problem is, when I call this fixture in a test to see if it's valid:

require 'test_helper'    class WeightClassTest < ActiveSupport::TestCase    def setup      @middlewight_men = weight_classes(:middleweight_men)    end      test "should be valid" do      assert @middleweight_men.valid?    end  end  

I get this error:

NoMethodError: undefined method `valid?' for nil:NilClass  

Ruby on Rails Rake test - Expected 762146111 to match 762146111

Posted: 02 Sep 2016 07:52 AM PDT

My test fail on:

assert_match @post.user_id, @user.id  

with strange error:

Expected 762146111 to match 762146111.  

I have tried to use with and w/o Integer() in creation and/or on match steps

require_tree argument must be a directory in a Rails 5 upgraded app

Posted: 02 Sep 2016 07:30 AM PDT

I just upgraded my app from Rails 4.2.7 to Rails 5.0.0.1. I used RailsDiff to make sure I had everything covered and I believe I did. So far everything has worked well up until the loading of my app.

Now I am seeing this error:

Sprockets::ArgumentError at /  require_tree argument must be a directory  

This is my application.css:

/*   * This is a manifest file that'll be compiled into application.css, which will include all the files   * listed below.   *   * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,   * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.   *   * You're free to add application-wide styles to this file and they'll appear at the bottom of the   * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS   * files in this directory. Styles in this file should be added after the last require_* statement.   * It is generally better to create a new file per style scope. *   *= require_tree .   *= require_self   */  

This is my application.js

// This is a manifest file that'll be compiled into application.js, which will include all the files  // listed below.  //  // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,  // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.  //  // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the  // compiled file. JavaScript code in this file should be added after the last require_* statement.  //  // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details  // about supported directives.  //  //= require jquery  //= require jquery_ujs  //= require turbolinks  //= require_tree .  

This is what the server log looks like:

Started GET "/" for ::1 at 2016-09-02 09:08:19 -0500    ActiveRecord::SchemaMigration Load (1.5ms)  SELECT "schema_migrations".* FROM "schema_migrations"    User Load (1.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 2], ["LIMIT", 1]]  Processing by ProfilesController#index as HTML    Rendering profiles/index.html.erb within layouts/application    Profile Load (1.6ms)  SELECT "profiles".* FROM "profiles"    Rendered profiles/index.html.erb within layouts/application (45.8ms)  Completed 500 Internal Server Error in 367ms (ActiveRecord: 6.3ms)      DEPRECATION WARNING: #original_exception is deprecated. Use #cause instead. (called from initialize at /.rvm/gems/ruby-2.3.1@myapp/gems/better_errors-2.1.1/lib/better_errors/raised_exception.rb:7)  DEPRECATION WARNING: #original_exception is deprecated. Use #cause instead. (called from initialize at /.rvm/gems/ruby-2.3.1myapp/gems/better_errors-2.1.1/lib/better_errors/raised_exception.rb:8)    Sprockets::ArgumentError - require_tree argument must be a directory:    sprockets (3.7.0) lib/sprockets/directive_processor.rb:182:in `rescue in block in process_directives'    sprockets (3.7.0) lib/sprockets/directive_processor.rb:179:in `block in process_directives'    sprockets (3.7.0) lib/sprockets/directive_processor.rb:178:in `process_directives'  

I am using no plugins of any kind. It is a fairly simple/vanilla app. The only styling is from the default scaffold.scss.

What could be causing this?

Rails - conditional display of html block

Posted: 02 Sep 2016 07:31 AM PDT

On my views I use 1 form that includes a block that renders comments. I do not want to run it when creating a new record. So, I tried conditions like so...

<% unless @annotation_id.nil? %>  <hr>  <div class="row">    <div class="col-md-8">      <h4>Comments</h4>      <%= render @annotation.comments %>    </div>      <div class="col-md-4">      <%= render 'comments/form' %>    </div>    </div>  <% end %>  

This however results in never displaying the block - also when the annotation record exists. What am I doing wrong?

Heroku isn't routing correct whilst cloud9 preview is working fine

Posted: 02 Sep 2016 07:46 AM PDT

Hope one of you can help me out on this one, since I've been breaking my head on it for a while.

I deployed my app to Heroku after trying it out on the cloud9 preview. The problem is that whenever I try to press the button to create a account for a paid subscription, I don't get linked to the page to fill in my credentials. However, on cloud9 this seems to be working fine.

I found the the sole difference between the two by hovering over the same buttons on the different platforms with my mouse.

On cloud9 I get: https://xxxxxxxx-xxxxx.xxxxxxx.xx/users/sign_up?plan=1

On Heroku I get: https://xxxxxxxx-xxxx-xxxxx.herokuapp.com/sign_up

So whenever I click the one on Heroku, I get my build-in flash message saying: Please select a membership plan to sign up!

To be more specific whereas the problem lies according to me, I think it's somewhere in the home.html.erb where the variable gets passed through. (added below)

So it seems that the routing isn't working correct on my Heroku, but I just can't figure out why. I've added my files below.

Hope someone can help me out on this one! Kind regards.

Gemfile

source 'https://rubygems.org'      # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.5'  # Use sqlite3 as the database for Active Record  gem 'sqlite3', group: [:development, :test]  # Use postgresql as the database for production  group :production do    gem 'pg'    gem 'rails_12factor'  end  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.1.0'  # See https://github.com/rails/execjs#readme for more supported runtimes  # gem 'therubyracer', platforms: :ruby    # Use jquery as the JavaScript library  gem 'jquery-rails'  # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks  gem 'turbolinks'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.0'  # bundle exec rake doc:rails generates the API under doc/api.  gem 'sdoc', '~> 0.4.0', group: :doc    # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    # Use Unicorn as the app server  # gem 'unicorn'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development    group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug'  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> in views    gem 'web-console', '~> 2.0'      # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'  end    ### ADDED GEMS ###    # Bootstrap Gem  gem 'bootstrap-sass', '~> 3.3.6'    # Devise Gem  gem 'devise'    # Font Awesome  gem 'font-awesome-rails'    # Use stripe for handling payments  gem 'stripe'    # Use figaro to hide secret keys  gem 'figaro'    ruby '2.3.0'  

routes.rb

Rails.application.routes.draw do    devise_for :users, controllers: { registrations: 'users/registrations' }    resources :users do      resource :profile    end    resources :contacts    get '/about' => 'pages#about'    root 'pages#home'  end  

pages_controller.rb

class PagesController < ApplicationController    def home      @trial_plan = Plan.find_by id: '1'      @pro_plan = Plan.find_by id: '2'    end      def about    end  end  

users/registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController    before_filter :select_plan, only: :new      def create      super do |resource|        if params[:plan]          resource.plan_id = params[:plan]          if resource.plan_id == 2            resource.save_with_payment          else            resource.save          end        end      end    end      private      def select_plan        unless params[:plan] && (params[:plan] == '1' || params[:plan] == '2')          flash[:notice] = "Please select a membership plan to sign up."          redirect_to root_url        end      end  end  

application.html.erb

<!DOCTYPE html>  <html>  <head>    <title>Ayris</title>    <%= stylesheet_link_tag    'application', media: 'all' %>    <%= javascript_include_tag "https://js.stripe.com/v2/", type: 'text/javascript' %>    <%= javascript_include_tag 'application' %>    <%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLIC_KEY %>    <%= csrf_meta_tags %>  </head>  <body>  ...        <%= link_to root_path, class: 'navbar-brand' do %>          <i class="fa fa-users"></i>          Ayris        <% end %>          ...          <% if user_signed_in? %>            ...          <% else %>            ...          <% if user_signed_in? %>            ...          <% end %>          <li><%= link_to "About", about_path %></li>          <li><%= link_to "Contact Us", new_contact_path %></li>        </ul>      </div><!-- /.navbar-collapse -->    </div>  </nav>    <div class="container">    <% flash.each do |key, value| %>      <%= content_tag :div, value, class: "alert alert-#{key}" %>    <% end %>      <%= yield %>  </div>    </body>  </html>  

home.html.erb

  <% if user_signed_in? %>      ...          <% if current_user.profile %>            ...          <% else %>            ...          <% end %>       ...    <% else %>      <div class="col-md-6">        <div class="well">          <h2 class="text-center">Trial Membership</h2>          <h4>Sign up for free and get trial access for a period of 10 days.</h4>          <br/>          <%= link_to "Sign up for Trial", new_user_registration_path(plan: @trial_plan), class: 'btn btn-primary btn-lg btn-block' %>        </div>      </div>      <div class="col-md-6">        <div class="well">          <h2 class="text-center">Pro Membership</h2>          <h4>Sign up for the pro account for €75/month and get access to all functions.</h4>          <%= link_to "Sign up for Pro", new_user_registration_path(plan: @pro_plan), class: 'btn btn-success btn-lg btn-block' %>        </div>      </div>    <% end %>  </div>  

Heroku - Setting 1 dyno costs money

Posted: 02 Sep 2016 07:43 AM PDT

Whenever I set 1 dyno up using this command

heroku ps:scale web=1  

Then I go to check my resources, I see that it costs me 7 dollars, I don't know why since it's a personal app not a an application in a heroku team

It's a ROR application, I'm using both PostgreSQL and MongoDB add-ons which are free

I need to use the 1 free dyno but I looked through the free plan and Dyno configuration on Heroku and I can't get anywhere, any help ?

Increase ActiveModel ID Range to 8 byte

Posted: 02 Sep 2016 07:13 AM PDT

I've been digging around to see how I could have all my newly and subsequent Model id's to have a limit of 8 byte. Answers show how to when adding a new table column; I want whenever I rails g migration ..... the id would automatically has a limit of 8 byte. Possible?

When creating a new model, I get:

ActiveModel::RangeError: 36565651767 is out of range for ActiveModel::Type::Integer with limit 4

Where to change this limit from 4 to 8?

Why before_save considered to be bad?

Posted: 02 Sep 2016 07:49 AM PDT

I am sorry if similar question have been asked already I couldn't find anything identical.

Thus, can someone tell me why before_save especially conditional one can to be considered bad, please?

before_save :something, if: Proc.new { self.abc == 'hello' }  

Therefore I understand why validation sometimes fits much better, however what I don't understand is why some people think that callbacks can to be a bad thing to use and they force you to write only validations but never make them conditional.

I personally think that there's can be far larger problem because this change can affect already existing entries and so it's okay to implement conditional validator or to provide if for before_save if you plan to modify data only in certain case. Why some people think it's not okay? Could someone help me with that?

Thank you very much!

Params not being saved in rails

Posted: 02 Sep 2016 07:40 AM PDT

Disclaimer: I am very new to Ruby + rails. I'm not sure if this is a bug, but my params variable always seems to be null. I am working on a large and unfamiliar codebase so I'm not sure if it's something else interfering or my own code; any suggestions would be welcome however.

In my routes file I have match '/proxy_request/:number/:ref' => 'proxies#show', via: :get- I was under the impression that this would store :number and :ref variables in params. However when my proxies#show function runs (below), params is an empty hash.

In case it probably is something else interfering with params, is there another way to pass :number and :ref to proxies#show?

class ProxiesController < ApplicationController      include Service      skip_before_action :restrict_access!      def show      binding.pry #params is null here      data = { date: Adapter.staging_date.get(params[:number], params[:ref])}      render json: data, content_type: "application/javascript", callback: @_request.env["QUERY_STRING"].match(/jQuery\d*_\d*/)    end    end  

.joins? .include? Rails Console

Posted: 02 Sep 2016 07:22 AM PDT

I'm trying to view a table in rails console and can't figure it out.

A cart has_many :line_items and a Line item belongs_to :cart. I'm trying to get a table that shows a cart_id with its containing line_items in the console. Is this possible?

Any help would be appreciated!

Thanks in advance.

Rails Associations: belongs_to has_many confusion

Posted: 02 Sep 2016 08:10 AM PDT

I've read through the following tutorial and found the curious line:

notice that the create function is written in such a way that there has be a @post before creating a @comment.

You can see the supporting controller code:

Class CommentsController < ApplicationController    ----    def create      @post = Post.find(current_post)      @comment = @post.comments.create(post_params)  ## 'Essential stuff'      respond_to do |format|        if @comment.save          format.html { redirect_to action: :index, notice: 'Comment was successfully created.' }          format.json { render :show, status: :created, location: @comment }        else          format.html { render :new }          format.json { render json: @comment.errors, status: :unprocessable_entity }        end       end    end    ----  end  

Indeed, "current_post" implies that the post was created BEFORE the comment.

But what if I want both to be created simultaneously? For example, suppose my USER has_many EMAILS, and each EMAIL belongs_to a USER. Then, when creating a new user, I may want to have an expandable form that allows the user to add one, two, three, or twenty emails while creating his account.

How could this be done?

Rails, use a form field to set something on the user registration (devise)

Posted: 02 Sep 2016 06:29 AM PDT

I would really like to add a form field "invite_code" to the user sign up form, but I don't know how to add the invite_code to the controller so that the application knows how to look for it?

The form in the sign up on the template would read:

<% form_for User.new do |f| %>     <span>Email:</span> <% f.email %><br>     <span>Name:</span> <% f.name %><br>     <span>Invite Code:</span> <% f.invite_code %><br>  <% end %>  

The "invite_code" isn't part of the database or anything, but in the user registration model, I want to put a:

before_save :invite_promo  def invite_promo      if @invite_code.present? && @invite_code == "special_person"          self.special_key = true      end  end  

Is there an easy way to look for form fields in the template using the model or controller?
So sorry...I'm new to Rails. Thank you so much in advance!

Getting uninitialized constant from Sidekiq worker

Posted: 02 Sep 2016 07:42 AM PDT

I'm missing something, just not sure what. Sidekiq is up and running fine, I can see it in my terminal.

I have this worker, defined in app/workers/sqs_worker.rb

class SqsWorker    include Sidekiq::Worker    require 'aws-sdk'      def perform      #do something    end  end  

And then in just a test file at app/test.rb I have the very simple code:

require 'sidekiq'    SqsWorker.new.perform_async  

When I run the test.rb file I get this error: uninitialized constant SqsWorker (NameError)

Where did I go astray? I'm running Sidekiq (4.1.4)

I tried killing the running processes and restarting both Sidekiq and Redis to no luck.

Rails - Submit form in iFrame when model is opened

Posted: 02 Sep 2016 06:55 AM PDT

I'm trying to use Yodlee's API which requires the submission of a form and use of an iFrame.

How would I have the form submit and load in an iFrame automatically when a user loads the model? Here is the initial (unworking) code that I have:

%myModal_fastlink.modal    %label{:for => "modal-1"}      %li Add Portfolio    %input#modal-1.modal-state{:type => "checkbox"}/    .modal-fade-screen      .modal-inner        .modal-close{:for => "modal-1"}        %iframe{:height => "100%", :name => "an_iframe", :src => "https://node.developer.yodlee.com/authenticate/restserver/", :width => "100%"}    %br  %form#rsessionPost{:action => "https://node.developer.yodlee.com/authenticate/restserver/", :method => "POST", target: "an_iframe"}    %input{name: "app", type: "hidden", value: "10003100"}    %input{name: "rsession", type: "hidden", value: current_user.yodlee.fastlink.rsession}    %input{name: "token", type: "hidden", value: current_user.yodlee.fastlink.token}    %input{name: "redirectReq", type: "hidden", value: "true"}  :javascript    function launch() {      $("#myModal_fastlink").modal();      document.getElementById('rsessionPost').submit();      }    $("#myModal_fastlink .btn-close").click(function() {      $("#myModal_fastlink").modal('toggle');    });  

Issue with passing params with link_to

Posted: 02 Sep 2016 06:02 AM PDT

I have a link_to with user_vkontakte_omniauth_authorize_path(:return_to_path => request.original_url), and it does properly link me to the action with the parameter in the url bar, but, in the linked action, when I try to params[:return_to_path] it returns nil. Byebug shows that params hash does not contain anything other than code, state, controller, action and permitted. What am I doing wrong?

ActionDispatch::Http::UploadedFile - string contains null byte

Posted: 02 Sep 2016 06:55 AM PDT

I am trying to process an image upload via AJAX request using fineuploader js library and CarrierWave gem. I receive the uploaded file in params[:qqfile] and it's an ActionDispatch::Http::UploadedFile. When I try to read its contents, I get an error. So I came with an ugly hack that makes it work. My model:

class Image < ActiveRecord::Base    mount_uploader :file, ImageUploader  end  

My controller code:

def create    file = params[:qqfile].read    file = params[:qqfile].read    @image = Image.new(file: file)    @image.save  end  

Basically, after calling read the second time all works fine. With a single read call I get the following error when I do Image.new(file: file):

ArgumentError - string contains null byte:    carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:114:in `path'    carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:145:in `exists?'    carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:94:in `size'    carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:136:in `empty?'    carrierwave (0.10.0) lib/carrierwave/uploader/cache.rb:119:in `cache!'    carrierwave (0.10.0) lib/carrierwave/mount.rb:329:in `cache'    carrierwave (0.10.0) lib/carrierwave/mount.rb:163:in `file='    carrierwave (0.10.0) lib/carrierwave/orm/activerecord.rb:39:in `file='    activerecord (4.2.7.1) lib/active_record/attribute_assignment.rb:54:in `_assign_attribute'    activerecord (4.2.7.1) lib/active_record/attribute_assignment.rb:41:in `block in assign_attributes'    activerecord (4.2.7.1) lib/active_record/attribute_assignment.rb:35:in `assign_attributes'    activerecord (4.2.7.1) lib/active_record/core.rb:566:in `init_attributes'    activerecord (4.2.7.1) lib/active_record/core.rb:281:in `initialize'    activerecord (4.2.7.1) lib/active_record/inheritance.rb:61:in `new'    app/controllers/admin/images_controller.rb:8:in `create'  

Although it works, I want to get rid of second read call. What can I do? I read https://github.com/FineUploader/server-examples/wiki/Rails---CarrierWave#method-a-use-hacked-stringio and I don't want to use these solutions since I think I'm very close to make it work the simple way - by improving my current code. They are also outdated and not sure I could make them work. Any suggestions are welcome.

ruby on rails - Ordering two models

Posted: 02 Sep 2016 06:15 AM PDT

I have two models image.rb and story.rb

I am trying to order them together.

stories_controller.rb looks like this:

def index      @stories = Story.all.order(:cached_votes_total => :desc)      @images = Image.all.order(:cached_votes_total => :desc)      @combined = (@stories + @images).sort_by {|record| record.created_at}  end      private      def story_params          params.require(:story).permit(:title, :content, :category)      end  


images_controller.rb looks like this:

private      def image_params          params.require(:image).permit(:title, :image, :image_file_name, :category)      end  

In my index.html.erb im tryign to order them both but i run into undefined method errors because they have different parameters.

<% @combined.each do |s| %>      ...          <% end %>  

is there a way to fix this?

Ruby on Rails App assets not loading HTTP 404

Posted: 02 Sep 2016 05:55 AM PDT

estimatemyproject.com is running on ruby on rails for more than 2 years without any problems. But just today it stopped loading assets . I searched online and tried

 rake assets:precompile --trace RAILS_ENV=production  

but it fails:

root@emp:/home/emp/current# rake assets:precompile --trace  RAILS_ENV=production  rake aborted!  /home/emp/emp/releases/20160127092918/config/application.rb:7: syntax error, unexpected ':', expecting ')'    Bundler.require(*Rails.groups(assets: %w(development test)))                                     ^  /home/emp/emp/releases/20160127092918/config/application.rb:7: syntax error, unexpected ')', expecting kEND    Bundler.require(*Rails.groups(assets: %w(development test)))                                                           ^  /home/emp/emp/releases/20160127092918/config/application.rb:60: syntax error, unexpected $end, expecting kEND  /home/emp/emp/releases/20160127092918/Rakefile:5:in `require'  /home/emp/emp/releases/20160127092918/Rakefile:5  /usr/lib/ruby/vendor_ruby/rake/rake_module.rb:25:in `load'  /usr/lib/ruby/vendor_ruby/rake/rake_module.rb:25:in `load_rakefile'  /usr/lib/ruby/vendor_ruby/rake/application.rb:501:in `raw_load_rakefile'  /usr/lib/ruby/vendor_ruby/rake/application.rb:82:in `load_rakefile'  /usr/lib/ruby/vendor_ruby/rake/application.rb:133:in `standard_exception_handling'  /usr/lib/ruby/vendor_ruby/rake/application.rb:81:in `load_rakefile'  /usr/lib/ruby/vendor_ruby/rake/application.rb:65:in `run'  /usr/lib/ruby/vendor_ruby/rake/application.rb:133:in `standard_exception_handling'  /usr/lib/ruby/vendor_ruby/rake/application.rb:63:in `run'  /usr/bin/rake:27  

Help me to debug this please! Need the assets to reload or refresh the cache somehow.

Thanks!

Actioncable Nginx and Puma WebSocket handshake: Unexpected response

Posted: 02 Sep 2016 05:54 AM PDT

I am trying to configure the server with rails 5, Nginx and Puma. The application is running fine but Actioncable is giving

WebSocket connection to 'ws://server_name.com/cable' failed:  Error during WebSocket handshake: Unexpected response code: 200  

Below are my nginx settings,

upstream app {    server unix:/tmp/app.sock fail_timeout=0;  }    server {      listen       80;      server_name  server_name.com;      try_files $uri/index.html $uri @app;      client_max_body_size 100M;      location @app {        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;        proxy_set_header Host $http_host;        proxy_redirect off;        proxy_pass http://app;        client_max_body_size 10M;      }        location /cable {         proxy_pass http://app/;         proxy_http_version 1.1;         proxy_set_header Upgrade $http_upgrade;         proxy_set_header Connection "Upgrade";      }        location ~ ^/(assets|uploads)/ {          root assets_path;          gzip_static on;          expires max;          add_header Cache-Control public;          add_header ETag "";          break;      }      error_page   500 502 503 504  /500.html;   }  

In rails in production.rb, I did the settings like below.

config.action_cable.url = 'ws://server_name.com/cable'  

Any help will be appreciated.

how to use has_one and belongs_to after array rails 4

Posted: 02 Sep 2016 07:14 AM PDT

I have assoications in a way that:

LessonPlan:

class LessonPlan < ActiveRecord::Base    belongs_to :teacher    belongs_to :subject  end  

Subject:

class Subject < ActiveRecord::Base    has_many :lesson_plans  end  

Student:

class Student < ActiveRecord::Base    belongs_to :user  end  

User:

class User < ActiveRecord::Base    has_one :student  end  

I am using:

@students = LessonPlan.find(params[:id]).subject.students  

which returns me all students but I need to get emails of these students that are in Users table.

When I try to use @students = LessonPlan.find(params[:id]).subject.students.user

it gives me error, however,

@students = LessonPlan.find(params[:id]).subject.students.first.user works

fine but it returns one user record only.

I need emails of all users not a single only.

query results are so far like this:

    2.2.3 :025 >   LessonPlan.find(65).subject.students.joins(:user)        LessonPlan Load (0.6ms)  SELECT  "lesson_plans".* FROM "lesson_plans" WHERE "lesson_plans"."id" = $1  ORDER BY "lesson_plans"."created_at" DESC LIMIT 1  [["id", 65]]        Subject Load (0.4ms)  SELECT  "subjects".* FROM "subjects" WHERE "subjects"."id" = $1 LIMIT 1  [["id", 6]]        Student Load (1.2ms)  SELECT "students".* FROM "students" INNER JOIN "users" ON "users"."id" = "students"."user_id" INNER JOIN "subject_students" ON "students"."id" = "subject_students"."student_id" WHERE "subject_students"."subject_id" = $1  [["subject_id", 6]]       => #<ActiveRecord::AssociationRelation [#<Student id: 1, user_id: 3,   name: "xxxxx", gender: "male", dob: "12-27-1988", contact_mobile: "67462627",   contact_home: "662627", street: "12 helifax estate", city: "helifax", state:   "toronto", zip_code: "07544", country: "United Arab Emirates",   student_number: "kaka", current_grade: "C+", student_avatar: nil, school_id:   1, facebook_url: "http://www.facebook.com", linked_in_url:   "http://www.linkedin.com", twitter_url: "http://www.twitter.com", created_at:   "2016-08-30 07:14:36", updated_at: "2016-08-30 07:19:44", slug: "kk-  student", profile_picture: "images.jpg">, #<Student id: 2, user_id: 6, name:   "vvvvvv", gender: "male", dob: "09-01-1985", contact_mobile: "55522",   contact_home: "5522627", street: "12 helifax estate", city: "helifax", state:   "toronto", zip_code: "07544", country: "United States", student_number:   "pianoo", current_grade: "3.5", student_avatar: nil, school_id: 1,   facebook_url: "", linked_in_url: "", twitter_url: "", created_at: "2016-09-02   12:02:45", updated_at: "2016-09-02 12:02:45", slug: "ii",   profile_picture: nil>]>   2.2.3 :026 >  

How to query a model based on multiple associated models

Posted: 02 Sep 2016 07:58 AM PDT

I have a rails application where I have following models -

City, Hotel, Restaurant, Park.

Associations are like this -

class City < ActiveRecord::Base     has_many :hotels   has_many :restaurants   has_many :parks    end  

I want to find all cities that have at least one hotel or restaurant or Park.

How do I write single query to fetch such cities ?

jQuery Mobile with Rails UJS to honor data-ajax="false" on links that are using data-method="delete"

Posted: 02 Sep 2016 06:19 AM PDT

Currently i am using jquery mobile in my website. when i try to logout than data-ajax=false not working. in all other links data-ajax= false working and request dont send in ajax. but the problem occurs only on logout link. it because of data-method = delete.

<a class="logout-link ui-link" data-ajax="false" data-method="delete" href="<%= logout_path %>"><%= t('layouts.pull_down_menu.signout') %><i class="fa fa-sign-out"></i></a>  

i get this output when i logout because data-ajax=false ignored by the rails and i get this output in link

http://localhost:3000/en/main_page#/en/logout

it not redirect correctly

i tried all things from this articles and issue pages here , here and here

but any solution not working for me or i don't know how to apply the solution.

Thanx in advance. and sorry for my bad english.

Rails, how add to method html/js?

Posted: 02 Sep 2016 07:56 AM PDT

For example, I have a lot of similar pages. With only one difference: on each of this page (they have different controller) they have different variable, what apply to this html.erb file.

For example, video post html.erb

<% for post in @posts_for_video>    here some html    and javascript    and also ruby code injection  <% end %>  

Video controller:

@posts_for_video = Post.where(photo: true)  

And my photos page:

<% for post in @post_for_photos >    same html as video    same js as video    and same ruby code as video  <% end %>  

Photo controller:

@posts_for_photo = Post.where(video: photo)  

So my question: Is there any possibility to put html+js+ruby_code to, for example application_controller.rb?

Or is there any possibility to pass variable to _some.html.erb as a parameter?

I think, what I'm looking for is (in application_controller.rb):

def posts_for_all(post_variable)    for post in post_variable      html: post.theme      js: post.animation      ruby: some methods    end  end  

Mongoid not saving hash property

Posted: 02 Sep 2016 08:10 AM PDT

I'm using Rails 4 and Mongoid 4. In my app I have a model I have a hash attribute. I'm trying to update this attribute like so:

user = User.find(id)  user['hash_attr']['another_attr'] = another_hash  user.save  

But the above code doesn't seem to get persisted in the database. If I print the object like so:

puts user['hash_attr']['another_attr']  

I get the right result, so there's no error but I try to load the model again (after the update):

user = User.find(id)  puts user['hash_attr']['another_attr']  

The attribute is not updated... I've seen this article but 1) is quite old so maybe there's something new on this area and 2) it didn't work for me.

Any suggestions?

Webhook test with CircleCI

Posted: 02 Sep 2016 04:52 AM PDT

Is there any good way that I can test webhook with CircleCI? I post some third party API and get webhook event out of it.

For local development, I just use ngrok but I'm not sure how can I integrate it with CircleCI.

How do I acces this join table in my search method?

Posted: 02 Sep 2016 04:35 AM PDT

My clients has_many regions, and my regions has_many clients. Through the join table Regionmemberships.

I want to filter through my clients and find the region_id's that I have clicked in my form. I can get it to work in my console, but not in my app.

The following code works when I try to manually filter through them in my console. I want a similar or same method in my find_results method in my search.rb model, but it seems as if :regionmemberships is not recognized as connected to my clients.

The console code that finds what I want:

results = Client.all  results = results.where(category_id: 3)  results = results.includes(:regionmemberships).where("regionmemberships.region_id" => "1")  

But if I try the same in my app, it throws me this error:

undefined local variable or method `"regionmemberships' for #<Search:0x007ffdd44e96c8>  

And refers to this error: (:regionmemberships is marked in the error-text)

def find_results      results = Client.order(:name)       results = results.where(visible: true)      results = results.where(category_id: category_id) if category_id.present?      results = results.includes(:regionmemberships).where("regionmemberships.region_id" => "0")     

This is how my app looks:

Models:

Client.rb  has_many :regionmemberships, :dependent => :destroy  has_many :regions, through: :regionmemberships  belongs_to :category    Region.rb  has_many :regionmemberships, :dependent => :destroy  has_many :clients, through: :regionmemberships    Regionmembership.rb  belongs_to :client  belongs_to :region    Category.rb  has_many :clients  

The relevant form in my new.html.erb view

new.html.erb  <%= f.collection_select :region_id,  Region.all, :id, :name, {include_blank: false},   {class: "regionclass", size: "1"} %>  

Searches_controller

  def new      @search = Search.new      def create      @search = Search.create!(search_params)      redirect_to @search     end      def show      @search = Search.find(params[:id])    end    def search_params      params.require(:search).permit(:category_id, :region, :regions, :regionmembership, :regionmemberships, :visible, :region_id, :pricerange1, :pricerange2, :pricerange3, :pricerange4, :pricerange5, region_ids: [])  end  

Search.rb (This is where I need to create a similar code to my console-example - But it seems like :regionmemberships doesnt exist / can't be found / referred to)

class Search < ApplicationRecord      def results          @results ||= find_results      end    private      def find_results          results = Client.order(:name) # Her skal ændres til position hvis visse clients ska          results = results.where(visible: true)          results = results.where(category_id: category_id) if category_id.present?          results = results.includes(:regionmemberships).where("regionmemberships.region_id" => "1")          end  end  

Hope anyone can help! It seems as if I need the app to understand that a client is connected to a :regionmemberships column. Thanks!!

Rails form_for only change controller

Posted: 02 Sep 2016 05:11 AM PDT

I would like to tell form_for to use a different controller without affecting the action.

I know how to change the URL like

form_for @car, url: { controller: 'admin/cars' }  

but this will also change the action.

Is there any way I can use a different controller with form_for without affecting the automatic choosing of the action?

NoMethodError in Users#index || database issue

Posted: 02 Sep 2016 05:02 AM PDT

I'm new to RoR. I've been following a tutorial where I had to generate scaffold user first_name last_name and then migrate to the DB. For some reason, when I tried to push to a new branch in Git, some of the changes were lost. Then I couldn't load the local server, getting an error related to the DB. After long hours trying to figure out what was wrong I gave up and decided to destroy and re-migrate the DB.

I've tried to generate scaffold user first_name last_name, but console gives me an error:

The name 'User' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative and run this generator again.  

Whilst the index page looks ok and I can create users and log in/log out normally, when I try to access http://localhost:3000/users/, I get this error:

NoMethodError in Users#index  Showing /Users/Jen/nameofapp/app/views/users/index.html.erb where line #16 raised:    undefined method `first_name' for # User:0x007febdf5938a0  

These are my code snippets:

views/users/index.html.erb

    <p id="notice"><%= notice %></p>    <h1>Listing Users</h1>    <table>      <thead>        <tr>          <th>First name</th>          <th>Last name</th>          <th colspan="3"></th>        </tr>      </thead>        <tbody>        <% @users.each do |user| %>          <tr>            <td><%= user.first_name %></td>            <td><%= user.last_name %></td>            <td><%= link_to 'Show', user , class:"btn btn-default btn-xs" %></td>            <td><%= link_to ('<span class="glyphicon glyphicon-pencil"></span>').html_safe, edit_user_path(user) %></td>            <td><%= link_to ('<span class="glyphicon glyphicon-remove"></span>').html_safe, user, method: :delete, data: { confirm: 'Are you sure?' } %></td>          </tr>        <% end %>      </tbody>    </table>  <br>    <div class="col-sm-6 col-md-4">    <%= link_to 'New User', new_user_path, class:"btn btn-default btn-xs" %>  </div>  

models/user.rb

    class User < ApplicationRecord          devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable          has_many :orders           end  

controllers/users_controller.rb

class UsersController < ApplicationController    before_filter :authenticate_user!, :except => [:show, :index]    before_action :set_user, only: [:show, :edit, :update, :destroy]    load_and_authorize_resource      # GET /users    # GET /users.json    def index      @users = User.all    end      # GET /users/1    # GET /users/1.json    def show    end      # GET /users/new    def new      @user = User.new    end      # GET /users/1/edit    def edit    end      # POST /users    # POST /users.json    def create      @user = User.new(user_params)        respond_to do |format|        if @user.save          format.html { redirect_to @user, notice: 'User was successfully created.' }          format.json { render :show, status: :created, location: @user }        else          format.html { render :new }          format.json { render json: @user.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /users/1    # PATCH/PUT /users/1.json    def update      respond_to do |format|        if @user.update(user_params)          format.html { redirect_to @user, notice: 'User was successfully updated.' }          format.json { render :show, status: :ok, location: @user }        else          format.html { render :edit }          format.json { render json: @user.errors, status: :unprocessable_entity }        end      end    end      # DELETE /users/1    # DELETE /users/1.json    def destroy      @user.destroy      respond_to do |format|        format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_user        @user = User.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def user_params        params.require(:user).permit(:first_name, :last_name)      end  end  

3 comments:

  1. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.
    Money manifestation technique

    ReplyDelete
  2. I would like to say that this blog really convinced me to do it! Thanks, very good post.
    Law of attraction 2021

    ReplyDelete
  3. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us to read this.
    Rodent control Toronto

    ReplyDelete