Sunday, July 3, 2016

rails rspec controller test with has_one relationship | Fixed issues

rails rspec controller test with has_one relationship | Fixed issues


rails rspec controller test with has_one relationship

Posted: 03 Jul 2016 08:09 AM PDT

Product :has_one company, company :belongs_to product. The following code works for my other has_one association, but for some reason it doesn't work here. In dev ENV the create action works fine. All the other controller tests (show,update,destroy...) and model tests pass. What can go wrong?

before(:each) do    login_user  end    ........    describe "POST create" do    let!(:profile) { create(:profile, user: @user) }    let!(:product) { create(:product, :product_with_nested_attrs, owner: @user) }      before(:each) do      if product.company.present?        product.company.destroy      end      request.env["HTTP_REFERER"] = new_product_company_path(product)    end      context "with vaild attributes" do      subject(:create_action) { post :create, product_id: product.id, company: attributes_for(:company, product: product) }         it "saves the new company in the db" do        expect{ create_action }.to change{ Company.count }.by(1)      end        it "redirects to back and shows the flash" do        create_action        expect(response).to redirect_to product_company_path(product)        expect(controller).to set_flash[:notice].to("Company successfully created!")      end    end  end  

Is render on controller the same than in views? how to call "view" render from controller?

Posted: 03 Jul 2016 08:08 AM PDT

I've a very simple js logic to implement when doing ajax request, so I've a respond_to block and I would like to specify the reply for js inline, so I tried to do this:

respond_to do |format|    format.html    format.js { render js: "$('ul#slides').append('#{j(render @slide)}');" }  end  

The problem is that this is throwing a doublicate render error, (as I have render inside a render), but, how this work if I put that piece of code in a view? how I can call the "view" render on a controller?

Jquery file upload taking time before sending the ajax request

Posted: 03 Jul 2016 07:23 AM PDT

I am following this tutorial to direct upload to AWS S3 using jquery file uploader and the upload works fine, but the issue is when I select a file or image to be uploaded and watch the console (firefox), it tooks some "long" seconds before the ajax request start processing.. I thought maybe something is wrong with my Rails app, so I created a simple html file and used the same code and I was surprised that the request runs (correctly) right after I select the file.

The last assumption was that something is wrong with other js libraries maybe, so I created a brand new Rails project and used only the code for the upload, but the same issue, the ajax request take some long seconds before start runing!

Rails v 4.2.6

any help ?

Rails: Rendering Sanitized Markdown

Posted: 03 Jul 2016 07:27 AM PDT

We are using Redcarpet to render views on our Rails 4.2.6 application.

To assure safe inputs we use sanitizing:

def markdown(text)    if text.present?      sanitize(markdown_renderer.render(text))    end  end    def markdown_renderer    Redcarpet::Markdown.new(Redcarpet::Render::HTML,                            no_intra_emphasis: true,                            fenced_code_blocks: true,                            autolink: true,                            tables: true,                            underline: true,                            highlight: true,                            with_toc_data: true)  end    def sanitize(input)    if input.present?      ActionView::Base.new.sanitize(input.html_safe)    end  end  

And it worked great, but then we got a request to put in tables. I realized that HTML-table tags are not allowed in the default sanitize implementation.

Our first solution was to add

config.action_view.sanitized_allowed_tags = %w( table tr th td )  

(if you try to do += or << you get a nil error, no default values?)

But this disallowed all the default tags, so now every tag needs to be explicitly added.

Is there a better way to solve this?

Either using some different technique for sanitizing or something else.

Ruby: Ignore last line of a file and add a row to an array

Posted: 03 Jul 2016 07:43 AM PDT

So, I have the following:

twodarray = []  File.open("SG_hum50_LODG.gro", "r") do |f|    f.each_line do |line|      textarray = line.split()      textarray[0],textarray[1],textarray[2] = textarray[1],textarray[0],textarray[2].to_i      textarray[1] = textarray[1].gsub(/:/, '').to_i      twodarray << textarray    end  end  

Which works pretty well. The problem I am having is I need to ignore the last line of the text file, and I need to add

["Sensor", "Timestamp", "Sensor Value"],  

As the first row in the array.

can't use form variables in the controller to save the select data

Posted: 03 Jul 2016 06:58 AM PDT

<tr>      <th><%=f.label(:id, "Choose car")%></th>      <td><%= f.select(:id, @cars_all.map{|c| [c.name, c.id]}) %></td>    </tr>    <tr>      <th><%=f.label(":list_id", "Choose List")%></th>      <td><%= f.select(:list_id, @lists.map{|s| [s.name, s.id]}) %></td>    </tr>  

i want to get the value of these two select values to use them in the contorller to add them in the database in a joint table,

@car_id = params[:id]  

doesn't work and doesn't get the data, and is there is away to echo these values

Ruby on Rails: How to store data in two tables following the creation of a record in one?

Posted: 03 Jul 2016 06:57 AM PDT

I have two database tables Users and Accounts, when a new user is created their primary email address that they will use to login is stored in the Users table. What I want to do is also store a copy of their primary email address in the Accounts table, as this table will be used to store the email addresses of that user.

I have tried the following in my users_controller:

class UsersController < ApplicationController      def index      @users = User.all    end      def show      @user = User.find(params[:id])    end      def new      @user = User.new    end      def edit      @user = User.find(params[:id])    end      def create      @user = User.new(user_params)      if @user.save                 session[:user_id] = @user.id          @account = Account.new(email: params[:primaryemailaddress], user_id: session[:user_id])          redirect_to @user      else          render 'new'      end    end      def update      @user = User.find(params[:id])        if @user.update(user_params)          redirect_to @user      else          render 'edit'      end    end      def destroy      @user = User.find(params[:id])      @user.destroy      redirect_to users_path    end      private      def user_params      params.require(:user).permit(:title, :firstname, :surname, :housenumber, :street, :city, :postcode, :organisation, :primaryemailaddress, :password)    end    end  

And the following in my User model:

class User < ActiveRecord::Base      has_many :accounts      accepts_nested_attributes_for :accounts      validates :primaryemailaddress, presence: true      has_secure_password  end  

So, as you can see in the create method in the users_controller, I am trying to create a new record in the Accounts table using the primary email address the user has entered on the registration form.

Can someone please tell me where I am going wrong?

Select option does not work in rails using materialize

Posted: 03 Jul 2016 06:47 AM PDT

I have a select option in my form_for in rails. It was working before I installed materialize but after installing it, it doesnt work anymore. I am a RnR beginner. Please see my code below:

Game model

 class Game < ActiveRecord::Base          GENRES = ['Action', 'Adventure', 'RPG', 'Simulation', 'Strategy', 'Sports', 'Others']        PLATFORMS = ['3DS', 'WII U', 'NX', 'PC', 'Playstation', 'XBOX', 'PS Vita', 'Mobile', 'Others']        end  

new.html.erb

<h1> Add Game </h1>        <%= form_for :game, url: games_path do |f| %>        Title: <%= f.text_field :title %> <br />        Genre: <%= f.collection_select :genre, Game::GENRES, :to_s, :to_s, :include_blank => true %> <br />        Platform: <%= f.collection_select :platform, Game::PLATFORMS, :to_s, :to_s, :include_blank => true %> <br />        Release Date: <%= f.date_field :release_date %> <br />        Progress: <%= f.number_field :progress %> <br />        Rating: <%= f.number_field :rating %> <br />          <%= f.submit 'Add Game', class: 'add_game_button' %>      <%end%>  

Rspec and factory girl: Factory already registered: my_model

Posted: 03 Jul 2016 05:59 AM PDT

I have this:

#spec/spec_helper.rb   require "support/factory_girl"    RSpec.configure do |config|    # .....  

And

#spec/support/factory_girl.rb  require "factory_girl_rails"    RSpec.configure do |config|    config.include FactoryGirl::Syntax::Methods  end  

And

# spec/rails_helper.rb  # This file is copied to spec/ when you run 'rails generate rspec:install'  ENV['RAILS_ENV'] ||= 'test'  require File.expand_path('../../config/environment', __FILE__)  # Prevent database truncation if the environment is production  abort("The Rails environment is running in production mode!") if Rails.env.production?  require 'spec_helper'  require 'rspec/rails'  # .......  

And my model spec:

require "spec_helper" in spec/models/my_model_spec.rb

RSpec.describe MyModel, type: :model do    context "fdsfdsfds" do      before do        @my_model = create(:my_model)      end        subject{ @my_model }        it { should respond_to(:aa) }      it { should respond_to(:bb) }    end  end  

The error I have:

/home/me/.gem/ruby/2.3.1/gems/factory_girl-4.7.0/lib/factory_girl/decorator.rb:10:in `method_missing':      Factory already registered: my_model (FactoryGirl::DuplicateDefinitionError)  

The gems are:

group :development, :test do    gem "rspec-rails", "~> 3.4"    gem "factory_girl_rails"  end  

I run it as just "rspec"

rails association proxy error

Posted: 03 Jul 2016 05:52 AM PDT

This error keeps displaying

So i have the association done actually has_many, belongs_to i have no idea why is this error showing up.

Restoraan.rb

class Restoraan < ActiveRecord::Base      has_many :kichens      has_many :atmospheres      has_many :resto_imgs      accepts_nested_attributes_for :resto_imgs, :kichens, :atmospheres      #serialize :resto_type, :restoKitchen  end  

Kichen.rb

class Kichen < ActiveRecord::Base      belongs_to :restoraan, dependent: :destroy  end  

When i do Restoraan.kichen in rails c i get a error

NoMethodError: undefined method `kichen' for #< Class:0x005648039a9038>

How do I upgrade my rails routes with member exceptions AND collections?

Posted: 03 Jul 2016 05:06 AM PDT

I want to do some routing and can't figure it out. (I'm migrating from 2.3.9 to 4.2.6!)

Limited Members, Some Collection

In 2.3 With

map.resources :contact, :only => :index, :collection => { :send_mail => :post  }  

I got...

send_mail_contact POST /contact/send_mail(.:format) {:action=>"send_mail", :controller=>"contact"}      index_contact GET  /contact/index(.:format)     {:action=>"index", :controller=>"contact"}      contact_index GET  /contact(.:format)           {:action=>"index", :controller=>"contact"}  

So I've tried

resources :contact, only: [:index] do    collection do      post 'send_mail'      # :index => :get,       # :send_mail => :post  }    end  end  

which gives...

send_mail_contact_index POST   /contact/send_mail(.:format)   contact#send_mail            contact_index GET    /contact(.:format)             contact#index  

?? How do I get rid of the _index for send_mail?

Then I tried

with_options(only: [:index]) do |opt|    opt.resources :contact do      collection do        post 'send_mail'      end    end  end  

Which gives the same!

send_mail_contact_index POST   /contact/send_mail(.:format)   contact#send_mail            contact_index GET    /contact(.:format)             contact#index  

===============================

No Members, Collection Only

Also I have a collection of pages (non-static)...

In 2.3 With

map.resources  :info, :except => :all, :collection => {          :about => :get,  :usage => :get, :privacy => :get, :kudos => :get }  

I got...

privacy_info GET    /info/privacy(.:format)   {:controller=>"info", :action=>"privacy"}    usage_info GET    /info/usage(.:format)     {:controller=>"info", :action=>"usage"}    kudos_info GET    /info/kudos(.:format)     {:controller=>"info", :action=>"kudos"}    about_info GET    /info/about(.:format)     {:controller=>"info", :action=>"about"}  

So I tried

resources :info, only: [] do    collection do      get 'about'      get 'usage'      get 'privacy'      get 'kudos'    end  end  

which gives...

    about_info_index GET    /info/about(.:format)          info#about      usage_info_index GET    /info/usage(.:format)          info#usage    privacy_info_index GET    /info/privacy(.:format)        info#privacy      kudos_info_index GET    /info/kudos(.:format)          info#kudos  

Again I have the _index! about_info_index_path instead of about_info_path.

Lots of answers about using except and only, but Not with collections.

Is there a bug somewhere, undocumented feature, or am I really missing something?

Thank you, Dirk

Could not find sprockets-3.6.2 in any of the sources (Bundler::GemNotFound) when doing docker-compose up

Posted: 03 Jul 2016 06:56 AM PDT

I am new to docker. I have an existing rails app and I want to dockerize it. Please help me, how can I solve this. I ran into this problem. I have posted the error when I run this.

redis_1    | 1:M 03 Jul 11:47:39.087 * The server is now ready to accept connections on port 6379  sidekiq_1  | /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find sprockets-3.6.2 in any of the sources (Bundler::GemNotFound)  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:85:in `map!'  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:85:in `materialize'  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:140:in `specs'  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:185:in `specs_for'  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:174:in `requested_specs'  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/environment.rb:18:in `requested_specs'  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/runtime.rb:13:in `setup'  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler.rb:127:in `setup'  sidekiq_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/setup.rb:18:in `<top (required)>'  sidekiq_1  |    from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  sidekiq_1  |    from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  backend_1  | /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:92:in `block in materialize': Could not find sprockets-3.6.2 in any of the sources (Bundler::GemNotFound)  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:85:in `map!'  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/spec_set.rb:85:in `materialize'  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:140:in `specs'  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:185:in `specs_for'  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/definition.rb:174:in `requested_specs'  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/environment.rb:18:in `requested_specs'  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/runtime.rb:13:in `setup'  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler.rb:127:in `setup'  backend_1  |    from /usr/local/bundle/gems/bundler-1.10.6/lib/bundler/setup.rb:18:in `<top (required)>'  backend_1  |    from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  backend_1  |    from /usr/local/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'  backend_sidekiq_1 exited with code 1  backend_backend_1 exited with code 1  

This is my Gemfile:

source 'https://rubygems.org'      gem 'unicorn', '~> 4.9'  gem 'pg', '~> 0.18.3'  gem 'sidekiq', '~> 4.0.1'  gem 'redis-rails', '~> 4.0.0'    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '4.2.6'  # Use sqlite3 as the database for Active Record  # gem 'sqlite3'  # 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  

When I started the build process, sprockets-3.6.2 was installed.

My Dockerfile :

# Use the barebones version of Ruby 2.2.3.  FROM ruby:2.2.3-slim    # Optionally set a maintainer name to let people know who made this image.  MAINTAINER Class and Objects <classandobjects@gmail.com>    # Install dependencies:  RUN apt-get update && apt-get install -qq -y build-essential nodejs libpq-dev postgresql-client-9.4 --fix-missing --no-install-recommends    # Set an environment variable to store where the app is installed to inside  # of the Docker image.  # CHANGE ALL INSTANCE OF 'backend' WITH YOUR PROJECT NAME  ENV INSTALL_PATH /backend  RUN mkdir -p $INSTALL_PATH    # This sets the context of where commands will be ran in and is documented  # on Docker's website extensively.  WORKDIR $INSTALL_PATH    # Ensure gems are cached and only get updated when they change. This will  # drastically increase build times when your gems do not change.  COPY Gemfile Gemfile  RUN bundle install    # Copy in the application code from your work station at the current directory  # over to the working directory.  COPY . .    # Provide dummy data to Rails so it can pre-compile assets.  RUN bundle exec rake RAILS_ENV=production DATABASE_URL=postgresql://user:pass@127.0.0.1/dbname SECRET_TOKEN=pickasecuretoken  #assets:precompile    # Expose a volume so that nginx will be able to read in assets in production.  VOLUME ["$INSTALL_PATH/public"]    # The default command that gets ran will be to start the Unicorn server.  CMD bundle exec unicorn -c config/unicorn.rb  

My docker-compose.yml :

postgres:    image: postgres:9.4.5    environment:      POSTGRES_USER: backend      POSTGRES_PASSWORD: yourpassword    ports:      - '5432:5432'    volumes:      - backend-postgres:/var/lib/postgresql/data    redis:    image: redis:3.0.5    ports:      - '6379:6379'    volumes:      - backend-redis:/var/lib/redis/data    backend:    build: .    links:      - postgres      - redis    volumes:      - .:/backend    ports:      - '8000:8000'    env_file:      - .backend.env    sidekiq:    build: .    command: bundle exec sidekiq -C config/sidekiq.yml    links:      - postgres      - redis    volumes:      - .:/backend    env_file:      - .backend.env  

my sidekiq.rb:

sidekiq_config = { url: ENV['JOB_WORKER_URL'] }    Sidekiq.configure_server do |config|    config.redis = sidekiq_config  end    Sidekiq.configure_client do |config|    config.redis = sidekiq_config  end  

Error ActiveRecord::Tasks::DatabaseAlreadyExists when running tests in Rails 5

Posted: 03 Jul 2016 05:48 AM PDT

I am in the process of upgrading a rails app from 4.2 to 5.0.0.

I have updated the bundle, and executed rails app:update

The app does not need a database, so it is configured with sqlite adapter. It worked before the upgrade.

Now - when I am trying to run tests, I get an error: ActiveRecord::Tasks::DatabaseAlreadyExists

I have tried:

  • removing the sqlite3 gem, and the config/database.yml file - but then it fails with other failures.
  • deleting the database files, same result.

Below is the output of trying to run a single test file.

$ rails test:clip  running: test/models/clip_test.rb  ruby -Ilib:test test/models/clip_test.rb  rails aborted!  ActiveRecord::Tasks::DatabaseAlreadyExists: ActiveRecord::Tasks::DatabaseAlreadyExists  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/tasks/sqlite_database_tasks.rb:11:in `create'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/tasks/sqlite_database_tasks.rb:31:in `ensure in purge'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/tasks/sqlite_database_tasks.rb:31:in `purge'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/tasks/database_tasks.rb:188:in `purge'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:369:in `block (3 levels) in <top (required)>'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:375:in `block (3 levels) in <top (required)>'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/rake_proxy.rb:13:in `block in run_rake_task'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/rake_proxy.rb:10:in `run_rake_task'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/commands_tasks.rb:51:in `run_command!'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands.rb:18:in `<top (required)>'  bin/rails:4:in `require'  bin/rails:4:in `<main>'  Errno::ETXTBSY: Text file busy @ unlink_internal - /vagrant/rails/playlist/db/test.sqlite3  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/tasks/sqlite_database_tasks.rb:22:in `drop'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/tasks/sqlite_database_tasks.rb:28:in `purge'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/tasks/database_tasks.rb:188:in `purge'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:369:in `block (3 levels) in <top (required)>'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:375:in `block (3 levels) in <top (required)>'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/rake_proxy.rb:13:in `block in run_rake_task'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/rake_proxy.rb:10:in `run_rake_task'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands/commands_tasks.rb:51:in `run_command!'  /home/ubuntu/.rvm/gems/ruby-2.3.1/gems/railties-5.0.0/lib/rails/commands.rb:18:in `<top (required)>'  bin/rails:4:in `require'  bin/rails:4:in `<main>'  Tasks: TOP => db:test:load => db:test:purge  (See full trace by running task with --trace)  Run options: --seed 20686    # Running:    ..    Finished in 0.053323s, 37.5073 runs/s, 75.0147 assertions/s.    2 runs, 4 assertions, 0 failures, 0 errors, 0 skips  Coverage report generated for Minitest to /vagrant/rails/playlist/coverage. 106 / 188 LOC (56.38%) covered.  

How to update a file/image in ROR using AWS S3?

Posted: 03 Jul 2016 03:41 AM PDT

I'm developing an image editing app in Ruby on Rails, and I want to update my image on AWS S3 cloud storage. Currently I have a system where the user signs in, then using Carrierwave uploader uploads the image on S3 using fog in production, then I have an AJAX call to the controller which triggers the editing using mini_magick gem, then finally reloading the image.

The problem is that I don't know how to reupload it on S3 (updating the image), locally it works fine, but the problem is in production on Heroku with S3.

One of the answers was this, but for me it doesn't work: (AWS::S3::S3Object.store 's3/path/to/untitled.txt', params[:textarea_contents_params_name], your_bucket_name).

This is my code:

def flip # controller      imagesource = params["imagesource"].to_s # URL        image = MiniMagick::Image.open("#{imagesource}")      image.combine_options do |i|        i.flip      end      # image.write "#{imagesource}" # development        # production      AWS::S3::Base.establish_connection!(          :access_key_id     => 'xxxxxxxxxxxxxx',          :secret_access_key => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'      )      AWS::S3::S3Object.store '#{imagesource}', image, 'mybucket'      AWS::S3::S3Object.store('#{imagesource}', open(image), 'mybucket') #2nd attempt        respond_to do |format|        format.json {render :json => {:result => image}}      end  end  

What is the best way to make a database based test maker?

Posted: 03 Jul 2016 04:03 AM PDT

I am a teacher at a school and I am planning about making test-maker. The blue-print for the application that I want to make is like this:

  1. There is a database that stores information of questions.(fields: question, answer, topic, level, score)
  2. You can add to the database by reading a csv file or a json file.
  3. You can make a test using the data from the database based on a query.
  4. You can style your test template as you like.
  5. Other teachers(users) can log in and add to the database.

I have done some research on how to make this and thought about using python-django or maybe ruby on rails. But I still can't decide what the best choice would be. I feel that django is a bit more difficult than rails but python's numpy, pandas library might be useful when I look into more complicated data research in the future. Someone told me that using node.js-meteor might be good because you only need to use one programming language.

I have experience in writing apps in VB and using SQL. I mainly use a mac.

It would be great if I could get some advice on how I should proceed.

Rails 5.0.0 Actioncable via Proxy

Posted: 03 Jul 2016 03:04 AM PDT

I have an chat application deployed to a vps with Puma and Nginx 1.10 my nginx config is the following:

upstream websocket {    server 127.0.0.1:28080;  }    server {    location /cable {      proxy_pass http://websocket/;      proxy_http_version 1.1;      proxy_set_header Upgrade $http_upgrade;      proxy_set_header Connection "Upgrade";    }  }  

This is my config.ru file for cable:

require ::File.expand_path('../../config/environment',  __FILE__)  Rails.application.eager_load!    ActionCable.server.config.disable_request_forgery_protection = true    run ActionCable.server  

In environment/production.rb

config.action_cable.allowed_request_origins = ['http://ahu.mydomain.ir', 'https://ahu.mydomain.ir']  config.action_cable.url = "ws://ahu.mydomain.ir/cable"  

My client connected to internet via a proxy server and in chrome console i get the following error:

WebSocket connection to 'ws://ahu.mydomain.ir/cable' failed: Establishing a tunnel via proxy server failed

In another client without proxy every thing is OK.

Can't disable Guard visual notifications for Rails project

Posted: 03 Jul 2016 03:01 AM PDT

Whenever I run a test in my Rails project, Guard activates one of its many 'visual notification' features and changes the background of my tmux status bar (green for passing, red for failing, and just on the lefthand side).

Before:

Original tmux status bar colors

After:

tmux 'notification' status bar colors

After a little bit of digging (i.e., finding this previously asked question), I discovered that this was a feature of Guard rather than a bug, so I set out to fix the configuration. According to this official documentation,

The Guardfile DSL is evaluated as plain Ruby, so you can use normal Ruby code in your Guardfile (and your ~/.guard.rb file which is evaluated first if it exists).

and, importantly,

Notifications can also be turned off in the Guardfile, in addition to setting the environment variable GUARD_NOTIFY or using the cli switch -n:

notification :off

NOTE: since notification is more of a user setting, it's best to have each team member set this in their own ~/.guard.rb file (instead of the project Guardfile).

So, I created a one-line ~/.guard.rb and Guardfile in the project root, consisting solely of the line notification :off, but the problem still persists. What else do I have to do to make Guard see its own config file?

Notes

I'm following Michael Hartl's Ruby on Rails Tutorial. This is the Gemfile, as he's specified it. It uses Minitest. No idea if that matters.

Devise related emails are not triggering devise rails

Posted: 03 Jul 2016 02:45 AM PDT

I have checked all the related articles but didn't find solution. Devise is not sending confirmation email when I am creating a user account through rails console. In logs I am only seeing insert statements, no logs for email. My smtp settings are working fine. My custom mails are triggering but devise emails are not triggered. Not even reset password. Please help

rails adding fields to 2 different tables which has many to many relation ship

Posted: 03 Jul 2016 05:20 AM PDT

i want to make 2 tables, list and cars, and the relation between them is many to many,

class CarsController < ApplicationController  layout "admin"    before_action :find_list   def index    @cars = @list.cars.all    @car_count = @list.cars.count   end     def show     @car = Car.find(params[:id])   end     def new     @car = Car.new({:list_id => @list.id, :name => "Default"})     @cars_all=Car.all     @lists = List.order ('Position ASC')   end   def create    @car = Car.new(car_params)    @cars_all=Car.all    if @car.save    @list.cars << @car            flash[:notice] = "Car created successfully"    redirect_to(:action => 'index', :list_id => @list.id)  else    @lists = List.order ('Position ASC')    render('new')  end  end    def edit    @car = Car.find(params[:id])    @lists = List.order ('Position ASC')    @cars_all=Car.all  end    def update    @car = Car.find(params[:id])    @cars_all=Car.all    if @car.update_attributes(car_params)      flash[:notice] = "Car Updated successfully"      redirect_to(:action => 'show', :id => @car.id, :list_id => @list.id)    else      @lists = List.order ('Position ASC')      render('edit')    end  end    def delete    @car = Car.find(params[:id])  end     def destroy    car = Car.find(params[:id]).destroy    flash[:notice] = "Car #{car.name} destoryed successfully"    redirect_to(:action => 'index', :list_id => @list.id)  end    private    def car_params      params.require(:car).permit(:list_id, :name)    end      def find_list      if params[:list_id]        @list = List.find(params[:list_id])      end    end    end  

How to SELECT name FROM sqlite_master WHERE (type = 'table' OR type = 'view') AND NOT name = 'sqlite_sequence' AND name = "schema_migrations"

Posted: 03 Jul 2016 02:44 AM PDT

now i am studying Rails tutorial 7.

There is a error :SQLite3::CorruptException: database disk image is malformed: SELECT name FROM sqlite_master WHERE (type = 'table' OR type = 'view') AND NOT name = 'sqlite_sequence' AND name = "schema_migrations"

(on localhost:3000)

I dont know how to solve this problem. Please tell me.

Thanks.

railsチュートリアルの7章をしている最中なのですが、 ローカルホストを開くと上記のエラーメッセージが出ます。 google先生に聞いても教えてくれず困っています。 どなたか解決策を知っている方がいたらよろしくお願いします。

Referencing rails assets without the digest?

Posted: 03 Jul 2016 02:19 AM PDT

I am referencing assets in my rails app directly, for ex. background-image: url('/assets/bg.png'). But I just realized this wouldn't work in production since digested assets are served (/assets/bg-dddasd434r4tfdfs...sada.png) in production. Is my only choice to use helper methods (for ex, image-url) throughout the application or is there a more simpler solution to this?

Namespaced class on rails' app folder

Posted: 03 Jul 2016 02:05 AM PDT

I have the following folder structure:

app  ├── assets  ├── controllers  ├── helpers  ├── mailers  ├── market_adapters  │   └── german.rb  │...  

And the file market_adapters/german.rb is:

module MarketAdapters #(I've also tried naming it singular)     class German     end  end  

When running tests I get the error:

/gems/activesupport-5.0.0/lib/active_support/dependencies.rb:512:in  `load_missing_constant': Unable to autoload constant German,   expected .../app/market_adapters/german.rb to define it (LoadError)  

Adding the market_adapters folder to the autoload_paths seems to have no effect config.autoload_paths << "#{Rails.root}/app/market_adapters"

If I move the market_adapters to the lib folder, everything works. But still would like to have it under app, any ideas?

By the way, I'm using Rails 5.

Search nearby users based on their last location

Posted: 03 Jul 2016 01:58 AM PDT

Currently, below is my model structure. With geocoder gem, I can do something like User.near([3.102, 101.1231], 30) to find users nearby that coordinate. However, it will only work if User has latitude and longitude columns. Based my my current model, I keep track of User locations, so a user have many locations.

If I use Location.near([3.102, 101.1231], 30), I still have to manually find only the latest location for a user from that query. Also, that query will go through all Location records, which over time, will become too big and make the query slow.

Is there any good way(s) that I can find users nearby a specific location?

class User < ActiveRecord::Base    has_many :locations  end    class Location < ActiveRecord::Base    belongs_to :location    # columns: user_id, latitude, longitude  end  

Assign Paperclip Attachment to Multiple Records In Model after_update Callback

Posted: 03 Jul 2016 05:05 AM PDT

I have products table and each product has category and attachment.

I'm using paperclip gem for attachments and my question is how can I assign the attachment to multiple products (products in the same category) once I create/update it in one of the products in the same category?

Note: I'm updating other string attributes through the model callbacks before_update & after_update and it's work, but I've tried to access the root_url in the Products model and tried to assign attachment to other products (which can be done just in controller not in model like this) even after add include Rails.application.routes.url_helpers in the Products model but without any result.

Dynamic ChartJS Chart Updated in Rails with AJAX

Posted: 03 Jul 2016 02:13 AM PDT

I am using Rails 5 and the latest ChartJS library (http://www.chartjs.org/docs/).

What I want to accomplish is to GET the latest 20 items from the SensorReading model and update the Chart with setInterval and AJAX.

I've built the AJAX call and I've loaded the Chart but I fail in two things.

First of of all I get a Syntax Error when reading data from Rails:

SyntaxError: expected expression, got '&'    var labels = [&quot;2016-07-03 10:33:49 +0300&quot;, &quot;2016-07-03 10:3  

No matter what I tried, they keep to appear with &quot; instead of quotes.

Secondly I am unable to update the Chart, as I need a handler available for the Chart itself to call .update() on it.

index.html.erb

<h1>Dashboard</h1>  <div class="ui divider"></div>    <div class="ui padded grid">    <div class="four wide column">      <div class="ui statistic">        <div class="value">          <%= @temperature %>.C        </div>        <div class="label">          TEMPERATURE        </div>      </div>      <br>      <div class="ui statistic">        <div class="value">          <%= @humidity %>%        </div>        <div class="label">          HUMIDITY        </div>      </div>    </div>    <div class="twelve wide column">      <div class="ui segment">        <div class="line-chart" style="max-height: 400px; display:block;">          <canvas id="updating-chart"></canvas>        </div>      </div>    </div>  </div>  <br>      <script>  var labels = <%= @sensor_readings.map(&:created_at) %>;    var canvas = document.getElementById('updating-chart'),      ctx = canvas.getContext('2d'),      startingData = {        labels: labels,        datasets: [            {                fillColor: "rgba(220,220,220,0.2)",                strokeColor: "rgba(220,220,220,1)",                pointColor: "rgba(220,220,220,1)",                pointStrokeColor: "#fff",                data: <%= @sensor_readings.map(&:temperature) %>            },            {                fillColor: "rgba(151,187,205,0.2)",                strokeColor: "rgba(151,187,205,1)",                pointColor: "rgba(151,187,205,1)",                pointStrokeColor: "#fff",                data: <%= @sensor_readings.map(&:humidity) %>            }        ]      },      latestLabel = startingData.labels[6];    // Reduce the animation steps for demo clarity.  var myLiveChart = new Chart(ctx , {      type: "line",      data: startingData,      animationSteps: 15  });    setInterval(function(){    // Add two random numbers for each dataset    //myLiveChart.data.datasets[0].data[2] = 50; // Would update the first dataset's value of 'March' to be 50    myLiveChart.update(); // Calling update now animates the position of March from 90 to 50.  }, 5000);    </script>  

dashboard.js

var ready = function(){      setInterval(refreshSensorReadings, 3000);      function refreshSensorReadings(){      console.log("--> Called");      $.rails.ajax({        type: "GET",        dataType: 'script',        url: "/sensor_readings_chart_data.js",        success: function(result){          //$('.line-chart').html(result);          console.log(result);        }      });    };      };    $(document).on('turbolinks:load', ready);  

route

get 'sensor_readings_chart_data', to: 'sensor_readings#chart_data'  

sensor_readings_controller.rb

def chart_data      @sensor_readings = SensorReading.last(20)      respond_to do |format|        format.json { head :no_content }        format.js        end    end  

Any advice will be appreaciated.

Binding Ethereum node into a Rails app, get 'JSON::ParserError: 776'

Posted: 03 Jul 2016 01:16 AM PDT

I'm new to the field, I'm trying ethereum-ruby to bind Ethereum node into a Rails app.

I have a node running APIs via IPC like

geth --ipcapi "admin,eth,debug,miner,net,shh,txpool,personal,web3"  

and in Rails console I can do

client = Ethereum::IpcClient.new("#{ENV['HOME']}/.ethereum/geth.ipc")  

but when I try puts client.coinbase["result"] I get and error:

JSON::ParserError: 776: unexpected token at '{"jsonrpc":"2.0","error":{"code":-32600,"message":"EOF"}}

Devise-invitable : Upon inviting a user, 2 emails are being sent, an invitation mail and a mail that says "Thank you for registering with us"

Posted: 03 Jul 2016 02:08 AM PDT

I am using Devise-invitable to send invitations to users using their email addresses. When I send and invitation, one of the mails that is (correctly) sent is one with the invitation link. However, another email gets sent which tells the invitee "Thank you for registering with us.".

I cannot find why this is happening.

Ruby version : 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]  Rails version : 4.2.4  devise version : 3.5.10  devise_invitable version : 1.6.0  

Code in invitations controller:

class InvitationsController < Devise::InvitationsController   def create    params[:user][:email].each do |email|      User.invite!({:email => email}, current_user) #If I comment out this line, both emails are not sent    end    redirect_to root_path   end  end  

ruby on rails: heroku: Missing `secret_key_base` for 'production' environment

Posted: 03 Jul 2016 01:29 AM PDT

I added the key into heroku config var, but I'm still getting the error.

Is this the correct way? I ignored secrets.yml as I read from other sources that its not a good idea to push this to the public.

in the heroku config var:

[key] SECRET_KEY_BASE  [value] 3280570382948240938  

in secrets.yml

production:    secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>  

What am I still doing wrong?

Furthermore, if I put my secret keys into heroku's config variable, don't other developers get to see this too? So, isn't that still kind of public? I've always wondered this concept.

rspec-rails+capybara NoMethodError:undefined method `create'

Posted: 03 Jul 2016 02:43 AM PDT

I'm learning ruby on rails, but I have a problem that I couldn't solve by myself. Any one can help me?

when I run:bundle exec rspec spec/models/user_spec.rb, I got this error:

Failure/Error: @user = create(:user)  NoMethodError:         undefined method `create' for #<RSpec::ExampleGroups::User::PropertiesShouldNotNil:0xb807450>       # ./spec/models/user_spec.rb:6:in `block (3 levels) in <top (required)>'  

Gemfile:

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '5.0.0.rc2'  # Use mysql as the database for Active Record  gem 'mysql2'  # 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', '~> 2.3.0'  # 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  gem 'alipay', '~> 0.10.0' #支付宝接口  gem 'capistrano-rails', :group => :development  gem 'capistrano-passenger', :group => :development  # 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'    # 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'    gem 'rspec-rails'    gem "capybara"  end  group :development do    gem 'web-console', group: :development  end  

spec/rails_helper.rb:

ENV["RAILS_ENV"] ||= 'test'  require 'spec_helper'  require File.expand_path("../../config/environment", __FILE__)  require 'rspec/rails'  require 'capybara/rails'  require 'capybara/rspec'    ActiveRecord::Migration.maintain_test_schema!    RSpec.configure do |config|      config.fixture_path = "#{::Rails.root}/spec/fixtures"      config.use_transactional_fixtures = true      config.infer_spec_type_from_file_location!  end  

app/models/user.rb

app/models/user.rb    has_many :recipients  end  

spec/models/user_spec.rb:

require 'rails_helper'    RSpec.describe User, type: :model do    context "properties should not nil" do      before do        @user = create(:user)      end        subject{ @user }        it { should respond_to(:name) }      it { should respond_to(:passwd) }    end  end  

Rails Correlated Subquery between two tables

Posted: 03 Jul 2016 12:34 AM PDT

I wrote following code. But it's not smart.

How to write in Rails AcriveRecord Way?

sql=<<-"EOS"  select shops.*, products.*  from shops, products   where   products.price = (select max(price) from products where shops.id = products.shop_id) and    shops.id = products.shop_id;  EOS    ret = ActiveRecord::Base.connection.select_all(sql)  

No comments:

Post a Comment