Saturday, December 10, 2016

How to solve NoMethodError in RailsAdmin::Main#index? | Fixed issues

How to solve NoMethodError in RailsAdmin::Main#index? | Fixed issues


How to solve NoMethodError in RailsAdmin::Main#index?

Posted: 10 Dec 2016 07:41 AM PST

When I try to use Rails Admin for articles. I'm getting the following error. This Image shows you the error I am facing

Here is articles_controller.rb

class ArticlesController < ApplicationController    before_action :set_article, only: [:show, :edit, :update, :destroy]    before_action :authenticate_auth_user!, except: [:index, :show]    # GET /articles    # GET /articles.json    def index      @articles=Article.all    end      # GET /articles/1    # GET /articles/1.json    def show    end      # GET /articles/new    def new      @article = Article.new    end      # GET /articles/1/edit    def edit    end      # POST /articles    # POST /articles.json    def create      @article = Article.new(article_params)        respond_to do |format|        if @article.save          format.html { redirect_to @article, notice: 'Article was successfully created.' }          format.json { render :show, status: :created, location: @article }        else          format.html { render :new }          format.json { render json: @article.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /articles/1    # PATCH/PUT /articles/1.json    def update      respond_to do |format|        if @article.update(article_params)          format.html { redirect_to @article, notice: 'Article was successfully updated.' }          format.json { render :show, status: :ok, location: @article }        else          format.html { render :edit }          format.json { render json: @article.errors, status: :unprocessable_entity }        end      end    end      # DELETE /articles/1    # DELETE /articles/1.json    def destroy      @article.destroy      respond_to do |format|        format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_article        @article = Article.find(params[:id])        @comments = @article.comments.all        @comment = @article.comments.build      end        # Never trust parameters from the scary internet, only allow the white list through.      def article_params        params.require(:article).permit(:title, :meta_description, :description, :category_id, :video)      end  end

And here is article.rb file in model

class Article    include Mongoid::Document    include Mongoid::Timestamps      has_many :comments    belongs_to :category      field :title, type: String    field :meta_description, type: String    field :description, type: String    field :category_id, type: String    field :video, type: String  end

Here is my gemfile

source 'https://rubygems.org'  ruby "2.3.1"    # Bundle edge Rails instead: gem 'rails', github: 'rails/rails'  gem 'rails', '~> 5.0.0', '>= 5.0.0.1'  # Use sqlite3 as the database for Active Record  gem 'sqlite3'  # Use Puma as the app server  gem 'puma', '~> 3.0'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0.6'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.2'  # 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 navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks  gem 'turbolinks', '~> 5'  # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder  gem 'jbuilder', '~> 2.5'  gem 'mongoid', '~>6.0.3'  gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'  gem 'friendly_id', '~> 5.2'  gem 'devise', '~> 4.2'  gem 'mail_form', '~> 1.6'  gem 'ckeditor', '~> 4.2'  gem 'rails_admin', '~> 1.1'  gem 'twitter-bootstrap-rails', '~> 3.2', '>= 3.2.2'  gem 'bootstrap-sass', '3.2.0.2'  gem 'less-rails', '~> 2.8'  gem 'therubyracer', '~> 0.12.2'  gem 'mongoid-ancestry', '~> 0.4.2'  gem 'simple_form', '~> 3.3', '>= 3.3.1'  # Use Redis adapter to run Action Cable in production  # gem 'redis', '~> 3.0'  # Use ActiveModel has_secure_password  # gem 'bcrypt', '~> 3.1.7'    # Use Capistrano for deployment  # gem 'capistrano-rails', group: :development  group :production do    gem 'pg', '~> 0.19.0'    gem 'rails_12factor', '~> 0.0.3'  end  group :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug', platform: :mri  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.    gem 'web-console'    gem 'listen', '~> 3.0.5'    # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring    gem 'spring'    gem 'spring-watcher-listen', '~> 2.0.0'  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

How can I solve this problem?

How to programmatically get current db schema

Posted: 10 Dec 2016 06:35 AM PST

How to programmatically get current db schema as struct or enumerable or some like this. I'd like to walk through schema and know list of tables and fields with types and indexes and so on. Please provide api reference or class name and method or path to file from root of repo to see.

Perform action each hour in Ruby on Rails app

Posted: 10 Dec 2016 07:24 AM PST

I have certain method that get some information from web and add it to DB. But I need to perform this method each hour. How can I do it in my rails app?

rails HABTM to has many through

Posted: 10 Dec 2016 06:15 AM PST

class QuestionSet    has_and_belongs_to_many :questions,                        class_name: 'Exam',                        join_table: 'question_question_sets',                        foreign_key: 'question_set_id',                        association_foreign_key: 'question_id'    end    class Question    has_and_belongs_to_many :question_sets,                        class_name: 'Exam',                        join_table: 'question_question_sets',                        foreign_key: 'question_id',                        association_foreign_key: 'question_set_id'    end  

The above models are inherited from the base model Exam(using rails STI) and the join table contains two fields: question_id and question_set_id. Now I need to convert this association into has_many through.

I have tried as follows:

class QuestionQuestionSet    has_many :questions    has_many :question_sets   end    class Question    has_many :question_question_sets, foreign_key: :question_id    has_many :question_sets, through: :question_question_sets   end    class QuestionSet    has_many :question_question_sets, foreign_key: :question_set_id    has_many :questions, through: :question_question_sets   end  

Rails is not sending custom font to browser

Posted: 10 Dec 2016 05:47 AM PST

I'm having problems to add custom fonts to a rails app. it doesn't work locally,. At my network tab i can't see my custom font being loaded.

font is stored at: /assets/fonts/Page-icon.ttf

Assets.rb:

Rails.application.config.assets.paths << "#{Rails.root}/app/assets/fonts"  Rails.application.config.assets.precompile += %w( .svg .eot .woff .ttf .otf)  

Application.rb:

config.assets.enabled = true  config.assets.paths << "#{Rails.root}/app/assets/fonts"  

Rails 5.0.0.1

thanks

Disable logging for column in activerecord/activejob 4.2

Posted: 10 Dec 2016 05:46 AM PST

is there any way to disable logging for certain columns in ActiveRecord/ActiveJob?

I'm using delayed_job to queue mailing jobs with attachments, but when having activerecord debug enabled (I need to have it on) the log is filled with the INSERT statements with the attachments encoded.

I was looking a this answer http://stackoverflow.com/a/21731809/6712797 but it doesn't seem to work, as I understand because when entering the log_with_binary_truncate method the sql is already populated and the binds array is empty, don't know if has something to do in how ActiveJob works.

In summary, i need to have debug enabled, but not log some column, or trim them if they are long (as the link provided), and I'm not talking about request parameters.

Thanks in advance

How to handle big Rails 5 application?

Posted: 10 Dec 2016 05:31 AM PST

I am assigned a task where I need to check the params are passed as Hash to the jobs.

Scenario:

Inside app/jobs there are 211 files.

I have to check which one have parameter called params. Then look at the name of that job inside the config/initializers/services.rb (CreatesSomethingJob probably maps to :creates_something).

Then, search inside the controllers for that service reference. If the service is being given params object, use params.to_unsafe_h instead of just params.

How would you tackle this? What is your way of doing it?

What is the easiest way to use MDI icons in my Rails 4 Project?

Posted: 10 Dec 2016 05:16 AM PST

I want to use MDI icons in my new Ruby on Rails 4 project.

  1. How I integrate MDI icons with my Rails code?

  2. What to include in my Gemfile?

https://materialdesignicons.com/ offer only NPM way.

It should be SASS or CDN way. Or, another way what best you prefer? Thanks.

Is it possible to set custom foreign key in Rails?

Posted: 10 Dec 2016 06:03 AM PST

I've searched a lot and tried to set as:

class Choco < ActiveRecord::Base    has_many :kinds, inverse_of: :choco, foreign_key: :myhash  

and

class Kind < ActiveRecord::Base    belongs_to :choco, foreign_key: :myhash  

So, I want to when I create a new kind, it will take myHash value from the Choco table and paste as a choco_id. But instead it pastes in that column NULL and I cannot understand why.

What is the problem?

Schema

For Choco:

— (id, title, myhash)  

For Kind:

— (id, choco_id, title)  

I want to paste myhash on choco_id field

one-to-many dynamic menu in rails

Posted: 10 Dec 2016 05:06 AM PST

I believe I am caught in a black zone between rails4 and rails 5 functionalities to generate dynamic menus. The grouped_collection_select for rails5 available on rails 4 I have working for many-to-many relationships... However

Consumo belongs_to :articolo  Consumo => attr_accessor :tipoarticolo_id  Articolo belongs_to :tipoarticolo  

the form to create a consumo calls

<%= collection_select(:consumo, :tipoarticolo_id, @tipoarticolos, :id, :tipoarticolo_label, {prompt: "do something"}) %>  <%= f.collection_select :articolo_id, @articolos, :id, :descrizione, prompt: "again" %>  

I have route

resources :consumos do    collection do      get :get_articolos, to: 'consumos#get_articolos'    end  end  

app/assets/javascripts/consumos.js.coffee is set

$(document).ready ->    $(".tipoarticolo_selection").on "change", ->      $.ajax        url: "/consumos/get_articolos"        type: "GET"        dataType: "script"        data:          tipoarticolo_id: $('.tipoarticolo_selection option:selected').val()  

to invoke app/views/consumos/get_articolos.js.erb

$('.tipoarticolo_selection').empty();  $('.tipoarticolo_selection').append( $('<option>scegliere articolo</option>'));  <% @articolos.each do |articolo| %>    $('.tipoarticolo_selection').append($('<option value="<%= articolo.id %>"><%= articolo.descrizione %></option>'));  <% end %>  

@articolos renders all the relevant option values, but does not react to a change in tipoarticolo_id (which is confirmed by the prompt string which does not change to the one of the js.erb file

consumos controller states

  def get_articolos      @magazzino = Magazzino.where('user_id = ?', current_user.id).first      @scortes = Scorte.where('magazzino_id = ?', @magazzino.id).pluck('articolo_id')      @articolos = Articolo.where("tipoarticolo_id = ? AND id IN (?)", params[:tipoarticolo_id], @scortes)    end  

Where have I missed something?

Rails carrierwave multiple file upload error

Posted: 10 Dec 2016 04:51 AM PST

I've been experiencing some issues with implementing multiple file uploads i've tried a few ways to get it to work namely the answers here Rails 4 multiple image or file upload using carrierwave. I couldn't get the first answer to work however i was able to get the second answer, and the one most similar to the carrierwave docs to add a entry to the database which looked like this; images: [{"tempfile"=>[], "original_filename"=>"Cinque_Deck-and-Jacuzzi.jpg", "content_type"=>"image/jpeg", "headers"=>"Content-Disposition: form-data; name=\"location[images][]\"; filename=\"Cinque_Deck-and-Jacuzzi.jpg\"\r\nContent-Type: image/jpeg\r\n"}, {"tempfile"=>[], "original_filename"=>"cooking.jpeg", "content_type"=>"image/jpeg", "headers"=>"Content-Disposition: form-data; name=\"location[images][]\"; filename=\"cooking.jpeg\"\r\nContent-Type: image/jpeg\r\n"}, {"tempfile"=>[], "original_filename"=>"hanging-rock.jpg", "content_type"=>"image/jpeg", "headers"=>"Content-Disposition: form-data; name=\"location[images][]\"; filename=\"hanging-rock.jpg\"\r\nContent-Type: image/jpeg\r\n"}]>

However when i try to display it, i get "NoMethodError in Locations#show", "undefined method `url' for #"

Can someone please tell me what i'm doing wrong? I've been working on this for days now and not getting anywhere.

The rest of my code is show.html.erb

    <%= image_tag @location.images[0].url, class: "display-location animated bounce" %>  <div class = "row hidden-sm-down">     <div class = "col-sm-4 hidden-sm-down">        <a href = "#" class = "thumbnail">           <%= image_tag @location.images[1].url %>        </a>     </div>     <div class = "col-sm-4">        <a href = "#" class = "thumbnail">           <%= image_tag @location.images[2].url %>        </a>     </div>     <div class = "col-sm-4">        <a href = "#" class = "thumbnail">           <%= image_tag @location.images[3].url %>        </a>     </div>  </div>  

schema.rb

    ActiveRecord::Schema.define(version: 20161210123055) do    enable_extension "plpgsql"      create_table "locations", force: :cascade do |t|      t.string   "name"      t.string   "address"      t.string   "website"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.string   "image"      t.text     "description"      t.string   "price"      t.json     "images"    end  

locations controller class LocationsController < ApplicationController .... # GET /locations # GET /locations.json def index @locations = Location.all @locations = @locations.paginate(:page => 1, :per_page => 2) end

  # GET /locations/1    # GET /locations/1.json    def show      @random_location = Location.where.not(id: @location).order("RANDOM()").first(3)      @reviews = Review.where(location_id: @location.id).order("created_at DESC")      if @reviews.blank?        @avg_rating = 0      else        @avg_rating = @reviews.average(:rating).round(2)      end    end      # GET /locations/new    def new      @location = Location.new    end      # GET /locations/1/edit    def edit    end      # POST /locations    # POST /locations.json    def create      @location = Location.new(location_params)        respond_to do |format|        if @location.save          format.html { redirect_to @location, notice: 'Location was successfully created.' }          format.json { render :show, status: :created, location: @location }        else          format.html { render :new }          format.json { render json: @location.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /locations/1    # PATCH/PUT /locations/1.json    def update      respond_to do |format|        if @location.update(location_params)          format.html { redirect_to @location, notice: 'Location was successfully updated.' }          format.json { render :show, status: :ok, location: @location }        else          format.html { render :edit }          format.json { render json: @location.errors, status: :unprocessable_entity }        end      end    end      # DELETE /locations/1    # DELETE /locations/1.json    def destroy      @location.destroy      respond_to do |format|        format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }        format.json { head :no_content }      end    end      private      # Use callbacks to share common setup or constraints between actions.      def set_location        @location = Location.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def location_params        params.require(:location).permit(:name, :price, :address, :website, :description, {images: []})      end        def check_user        unless current_user.admin?          redirect_to root_url, alert: "Sorry currently only admins have that functionality"        end      end  end  

Thanks,

Ruby on Rails page control

Posted: 10 Dec 2016 04:16 AM PST

I'm sorry, my English is bad. Question: i have model Pages with columns title, description etc. I can create, change, destroy this pages. I can see the contents of the link mydomian/pages/1. I need for each page has been template and rout, so i can see the content on the link, example maydomian/contacts. How to do it? Help me please.

How to check logs for Rails application on Unicorn and Nginx?

Posted: 10 Dec 2016 02:57 AM PST

I'm facing issue with one part of application which doesn't exist when I run application from production environment on localhost but there are no logs presented in /log folder.

Application is running on DigitalOcean with Debian 8 droplet.

Ruby method doesn't seem to return value

Posted: 10 Dec 2016 03:02 AM PST

I'm new to Ruby (and Rails), and I'm trying to take the form data from the view file and calculate something in the controller, but no value seems to be returned by the method. I have a feeling it's something very simple that I'm overlooking.

This is inside a def create:

    def calcQuadrant            important = params[:task][:important] # INT of 0 or 1          urgent = params[:task][:urgent] # INT of 0 or 1            if important == 1 && urgent == 1              return 1          elsif important == 1 && urgent == 0              return 2          elsif important == 0 && urgent == 1              return 3          elsif important == 0 && urgent == 0              return 4          end      end  

calcQuadrant doesn't seem return anything, even when I put important or urgent to the console and they have values. I'm ultimately trying to assign the value returned by calcQuadrant to a new param: params[:task][:quadrant].

At a high level, what I'm really trying to figure out is the best way for passing a param to the model which wasn't passed to the controller from the view. Is the best way to do that just assigning a value to that param in the controller? For example, I ask the user for a 'to-do' and whether the to-do is 'important' and/or 'urgent'. Based on their choices, I calculate a quadrant for the task to go into. Rather than saving the importance and urgency of the to-do in the DB, I just want to save the quadrant.

Rails engine dependencies not loading properly when using Cucumber

Posted: 10 Dec 2016 02:07 AM PST

I'm developing a Rails 5 engine (https://github.com/Sento/sento-kanban) using a "normal" Rails 5 application mounting the engine from the local disk.

Now I'm looking to add automated testing using Cucumber and I'm facing a dependencies loading issue when running the first scenario, and the first step which is visiting the root page of the app:

$ ccucumber  Using the default profile...  Feature: Create a new board  In order to manage my projects  As a project manager  I want to create a new board      Scenario: Try to create a new board without a title                 # features/boards/create_a_board.feature:6      Given I'm creating a board with an empty title                    # features/step_definitions/board_steps.rb:1        File to import not found or unreadable: perfect-scrollbar.        Load paths:          /application/spec/test_app/app/assets/config          /application/spec/test_app/app/assets/images          /application/spec/test_app/app/assets/javascripts          /application/spec/test_app/app/assets/stylesheets          /application/app/assets/config          /application/app/assets/images          /application/app/assets/javascripts          /application/app/assets/stylesheets          /usr/local/bundle/gems/unobtrusive_flash-3.3.1/lib/assets/javascripts          /usr/local/bundle/gems/unobtrusive_flash-3.3.1/lib/assets/stylesheets          /usr/local/bundle/gems/pace-rails-0.1.3/vendor/assets/javascripts          /usr/local/bundle/gems/pace-rails-0.1.3/vendor/assets/stylesheets          /usr/local/bundle/gems/modal-responder-rails-1.0.3/vendor/assets/javascripts          /usr/local/bundle/gems/modal-responder-rails-1.0.3/vendor/assets/stylesheets          /usr/local/bundle/gems/perfect-scrollbar-rails-0.6.15/vendor/assets/javascripts          /usr/local/bundle/gems/perfect-scrollbar-rails-0.6.15/vendor/assets/stylesheets          /usr/local/bundle/bundler/gems/dragula-rails-9417236588b6/vendor/assets/javascripts          /usr/local/bundle/bundler/gems/dragula-rails-9417236588b6/vendor/assets/stylesheets          /usr/local/bundle/gems/actioncable-5.0.0.1/lib/assets/compiled          /usr/local/bundle/gems/bootstrap-4.0.0.alpha5/assets/stylesheets          /usr/local/bundle/gems/bootstrap-4.0.0.alpha5/assets/javascripts          /usr/local/bundle/gems/bootstrap-4.0.0.alpha5/assets/stylesheets (ActionView::Template::Error)        ./app/assets/stylesheets/sento/kanban/application.scss:22        ./app/views/layouts/sento/kanban/application.html.slim:11:in `__application_app_views_layouts_sento_kanban_application_html_slim___2646165938008234128_69844567400820'        ./features/step_definitions/web_steps.rb:2:in `/^(?:|I )go to (.+)$/'        ./features/step_definitions/board_steps.rb:2:in `/^I'm creating a board with an empty title$/'        features/boards/create_a_board.feature:7:in `Given I'm creating a board with an empty title'  

Regarding the paths, I'm using Docker, mounting the project as /application/

It seems the engine dependencies aren't loaded.

Even worst, when I comment the lines requiring perfect-scrollbar and all the other external libraries, keeping only the import of the engine's style/*, it also say it cannot find this folder.

Can anyone give me a direction in order to solve this?

How to get rows with a distinct column in Rails

Posted: 10 Dec 2016 01:25 AM PST

How do I make a query that will give me all columns of a row, while a specific column is distinct amongst the results?

I have User and Message models where each user has many messages. I want to retrieve one message for each distinct from (phone number represented as a string).

If I use user.messages.select(:from).distinct this gives me one message for each distinct from, but I only have the from attribute available. Current result:

[#<Message id: nil, from: "+12033189163">, #<Message id: nil, from: "+12033189166">]  

Instead I want the query to return all the attributes/columns for each row.

Temporarily I am just running:

user.messages.group_by(&:from).map { |_, thread| thread.first }  

which works for now but I think is bad because it is loading every message instead of just one for each group.

Is there a better, and more efficient way?

Rails: merge simplecov results gives RuntimeError (can't modify frozen object)

Posted: 10 Dec 2016 12:36 AM PST

I'm trying to use simplecov to check code coverage by tests in Rails application. So I bumped into common problem: the uncovered files are not shown in the report. Adding Rails.application.eager_load! to test_helper.rb as well as changing config/environments/test.rb (solutions for this question: Simple cov gem missing untested files in Rails) didn't work for me.

I tried the solution proposed here: https://github.com/colszowka/simplecov/issues/16#issuecomment-31076575

Now my test_helper.rb looks like this:

require 'simplecov'  SimpleCov.start do     add_group 'Controllers', 'app/controllers'    add_group 'Models', 'app/models'    add_group 'Helpers', 'app/helpers'    add_group 'Mailers', 'app/mailers'    add_group 'Views', 'app/views'  end      all_files = Dir['**/*.rb']  base_result = {}  all_files.each do |file|  absolute = File::expand_path(file)  lines = File.readlines(absolute, :encoding => 'UTF-8')  base_result[absolute] = lines.map do |l|    l.strip!    l.empty? || l =~ /^end$/ || l[0] == '#' ? nil : 0  end  end      SimpleCov.at_exit do  merged = SimpleCov::Result.new(Coverage.result).original_result.merge_resultset(base_result)  result = SimpleCov::Result.new(merged)  result.format!  end      #Rails.application.eager_load!    ENV['RAILS_ENV'] ||= 'test'  require File.expand_path('../../config/environment', __FILE__)   require 'rails/test_help'     class ActiveSupport::TestCase     # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.     fixtures :all       # Add more helper methods to be used by all tests here...   end  

Now after calling rails test I get the error:

Running via Spring preloader in process 17211  Run options: --seed 8726    # Running:    ...................................    Finished in 3.251970s, 10.7627 runs/s, 15.6828 assertions/s.    35 runs, 51 assertions, 0 failures, 0 errors, 0 skips  /var/lib/gems/2.3.0/gems/simplecov-0.12.0/lib/simplecov/merge_helpers.rb:29:in `extend_object': can't modify frozen object (RuntimeError)      from /var/lib/gems/2.3.0/gems/simplecov-0.12.0/lib/simplecov/merge_helpers.rb:29:in `extend'      from /var/lib/gems/2.3.0/gems/simplecov-0.12.0/lib/simplecov/merge_helpers.rb:29:in `block in merge_resultset'      from /var/lib/gems/2.3.0/gems/simplecov-0.12.0/lib/simplecov/merge_helpers.rb:28:in `each_key'      from /var/lib/gems/2.3.0/gems/simplecov-0.12.0/lib/simplecov/merge_helpers.rb:28:in `merge_resultset'      from /home/tamila/Ruby/workspace/books_app/test/test_helper.rb:24:in `block in <top (required)>'      from /var/lib/gems/2.3.0/gems/simplecov-0.12.0/lib/simplecov/defaults.rb:67:in `block in <top (required)>'      from /var/lib/gems/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:161:in `fork'      from /var/lib/gems/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:161:in `serve'      from /var/lib/gems/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:131:in `block in run'      from /var/lib/gems/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:125:in `loop'      from /var/lib/gems/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:125:in `run'      from /var/lib/gems/2.3.0/gems/spring-1.7.2/lib/spring/application/boot.rb:19:in `<top (required)>'      from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'      from -e:1:in `<main>'  

Is there a way either to fix this error or to load the files without this bunch of code?

How do I enable :recoverable in Devise?

Posted: 10 Dec 2016 12:05 AM PST

By default, the forgot password in Devise doesn't actually send a password reset link to email and I know the :recoverable module is what needs to be enabled/implemented.

I have tried searching for tutorials or guides in google and here in stackoverflow but no success.

Where can I find a good example or what code do I need to enable it?

How to use modal with login?

Posted: 09 Dec 2016 10:22 PM PST

How can I use modal with login?

<%= link_to login_path, data: { modal: true } do %>    Log in via Email  <% end %>  

sessions_controller

  def new      @session = ??? # Model.new is what it should be but Session isn't a model so I don't know what to put instead to work with tutorial (cited below)      respond_modal_with @session    end      def create      user = User.find_by(email: params[:session][:email].downcase)      if user && user.authenticate(params[:session][:password])        log_in user        params[:session][:remember_me] == 'nil' ? forget(user) : remember(user)      else        flash[:alert] = 'INVALID EMAIL/PASSWORD COMBINATION'        render 'new'      end    end  

application_controller

  def respond_modal_with(*args, &blk)      options = args.extract_options!      options[:responder] = ModalResponder      respond_with *args, options, &blk    end  

routes

get 'login'   => 'sessions#new'  post 'login'   => 'sessions#create'  delete 'logout'  => 'sessions#destroy'  

sessions/new

<%= simple_form_for(:session, url: login_path, html: { data: { modal: true } }) do |f| %>    Test  <% end %>  

I followed this tutorial to implement modal code: http://www.jetthoughts.com/blog/tech/2014/08/27/5-steps-to-add-remote-modals-to-your-rails-app.html. It works elsewhere on my app.

Can't install Jekyll on Mint

Posted: 09 Dec 2016 07:48 PM PST

I installed ruby and ruby gems, updated both of them, tried to install jekyll using the command

sudo gem install jekyll bundler  

it gave me this

Building native extensions.  This could take a while...  ERROR:  Error installing jekyll:      ERROR: Failed to build gem native extension.        current directory: /var/lib/gems/2.3.0/gems/ffi-1.9.14/ext/ffi_c  /usr/bin/ruby2.3 -r ./siteconf20161209-4826-wdshax.rb extconf.rb  checking for ffi.h... *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:      --with-opt-dir      --without-opt-dir      --with-opt-include      --without-opt-include=${opt-dir}/include      --with-opt-lib      --without-opt-lib=${opt-dir}/lib      --with-make-prog      --without-make-prog      --srcdir=.      --curdir      --ruby=/usr/bin/$(RUBY_BASE_NAME)2.3      --with-ffi_c-dir      --without-ffi_c-dir      --with-ffi_c-include      --without-ffi_c-include=${ffi_c-dir}/include      --with-ffi_c-lib      --without-ffi_c-lib=${ffi_c-dir}/lib      --with-libffi-config      --without-libffi-config      --with-pkg-config      --without-pkg-config  /usr/lib/ruby/2.3.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError)  You have to install development tools first.      from /usr/lib/ruby/2.3.0/mkmf.rb:587:in `try_cpp'      from /usr/lib/ruby/2.3.0/mkmf.rb:1091:in `block in have_header'      from /usr/lib/ruby/2.3.0/mkmf.rb:942:in `block in checking_for'      from /usr/lib/ruby/2.3.0/mkmf.rb:350:in `block (2 levels) in postpone'      from /usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'      from /usr/lib/ruby/2.3.0/mkmf.rb:350:in `block in postpone'      from /usr/lib/ruby/2.3.0/mkmf.rb:320:in `open'      from /usr/lib/ruby/2.3.0/mkmf.rb:346:in `postpone'      from /usr/lib/ruby/2.3.0/mkmf.rb:941:in `checking_for'      from /usr/lib/ruby/2.3.0/mkmf.rb:1090:in `have_header'      from extconf.rb:16:in `<main>'    To see why this extension failed to compile, please check the mkmf.log which can be found here:      /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/ffi-1.9.14/mkmf.log    extconf failed, exit code 1    Gem files will remain installed in /var/lib/gems/2.3.0/gems/ffi-1.9.14 for inspection.  Results logged to /var/lib/gems/2.3.0/extensions/x86_64-linux/2.3.0/ffi-1.9.14/gem_make.out  Successfully installed bundler-1.13.6  Parsing documentation for bundler-1.13.6  Done installing documentation for bundler after 7 seconds  1 gem installed  

Here is what it says in the log file:

package configuration for libffi is not found  "gcc -o conftest -I/usr/include/x86_64-linux-gnu/ruby-2.3.0 -I/usr/include/ruby-2.3.0/ruby/backward -I/usr/include/ruby-2.3.0 -I. -Wdate-time -D_FORTIFY_SOURCE=2   -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -fPIC conftest.c  -L. -L/usr/lib/x86_64-linux-gnu -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fstack-protector -rdynamic -Wl,-export-dynamic     -lruby-2.3  -lpthread -lgmp -ldl -lcrypt -lm   -lc"  In file included from /usr/include/ruby-2.3.0/ruby/ruby.h:36:0,                   from /usr/include/ruby-2.3.0/ruby.h:33,                   from conftest.c:1:  /usr/include/ruby-2.3.0/ruby/defines.h:26:19: fatal error: stdio.h: No such file or directory  compilation terminated.  checked program was:  /* begin */  1: #include "ruby.h"  2:   3: int main(int argc, char **argv)  4: {  5:   return 0;  6: }  /* end */  

I'm running Linux Mint, and I can't find anything to help this problem. One gem of jekyll is installed and I'm able to create jekyll projects, but only partially and I can't run it on my local host and edit it.

Any more questions let me know and I'll try my best to help provide the details.

how to perform a background job rails?

Posted: 09 Dec 2016 10:42 PM PST

I've got a campaign table with a start date and end date. How do I go about running a daily task that would basically flip a boolean 'active' value in the table from true to false when the current date is greater than the end date.

I haven't dealt with any background tasks, just wondering how that is done.

Remotipart ( + Carrierwave) not uploading files nor using ajax

Posted: 09 Dec 2016 06:17 PM PST

I've spent a week right now trying to get this to work, reading as much as I can about remotipart, and trying to set it right, but I have failed miserably. I have form which has a title, description, an audio file and an image file. If I submit the form without remote: true it works perfectly, but once I try to upload the form with ajax, it seems like the files are not being uploaded.

Since I made the audio file a requirement for posting, I get redirected to the new action, displaying the error indicating that 'audio' must not be blank.

Even if I remove this validation from the model, once I try to upload, there is no audio file being uploaded.

Also, by checking the developer tools, I've realized that the response I'm getting is not javascript, but html.

I've already tried other gems, like jquery-uploadfile-rails, but none of them work for me for different reasons. I have no idea what to do right now.

_form.html.erb

<%= form_for(post, html: {multipart: true, remote: true}, authenticity_token: true) do |f| %>    <div id="form-content">      <div class="input-group field">          <span class="input-group-addon"><%= f.label 'Title' %></span>          <%= f.text_field :title, class: "form-control", placeholder: "Title" %>      </div>        <div class="input-group field">          <span class="input-group-addon"><%= f.label :descrption %></span>          <%= f.text_field :description, class: "form-control", placeholder: "Brief Description" %>      </div>        <div class="input-group field">          <span class="input-group-addon"><%= f.label :audio %></span>          <%= f.file_field :audio, class: "filestyle", 'data-iconName' => "glyphicon glyphicon-music", 'data-buttonText' => "Browse" %>      </div>        <div class="input-group field">          <span class="input-group-addon"><%= f.label :art %></span>          <%= f.file_field :art, class: "filestyle", 'data-iconName' => "glyphicon glyphicon-picture", 'data-buttonText' => "Browse" %>      </div>          <%= button_tag(type: 'submit', class: "btn btn-block btn-primary", id: "btn-post") do %>          <span class="icon-ok icon-white"></span> Post now!      <% end %>    </div>  <% end %>  

posts_controller.rb

def create      @post = Post.new(post_params)      @post.user_id = current_user.id      respond_to do |format|          if @post.save              format.html { redirect_to action: 'index' }              format.js              format.json { render :show, status: :created, location: @post }          else              format.html { render :new }              format.js              format.json { render json: @post.errors, status: :unprocessable_entity }          end      end  end  

create.js.erb

// Display a Javascript alert  alert('success!');  <% if remotipart_submitted? %>      alert('submitted via remotipart')  <% else %>      alert('submitted via native jquery-ujs')  <% end %>  

Lastly, I'm still learning about rails, it's arquitechture, and the 'rails way'. Even though I've been trying to do everything correctly, I'm pretty sure I have been improvising some parts, trying to solve errors. If you find anything weird and feel like sharing, I'll be completely open to learn the good way. If you need to check any other part of my code just tell me. Thanks!

PermanentRedirect Exception: aws-sdk s3 Rails 5

Posted: 09 Dec 2016 10:23 PM PST

I'm trying to list or retrieve objects from an amazon bucket and I keep getting this error message:

(byebug) resp = s3.list_objects(bucket:'mp3list')  *** Aws::S3::Errors::PermanentRedirect Exception:   The bucket you are attempting to access must be addressed   using the specified endpoint.   Please send all future requests to this endpoint.  

I can upload and delete files from the same bucket with no problem.

Does someone know how to specify that endpoint? and where?

My configuration of the s3 bucket:

Bucket: mp3play  Region: Frankfurt  Creation Date:  Fri Dec 09 17:44:39 GMT+100 2016  Owner: aaa    Can list, upload, delete.  

aws.rb >

Aws.config.update({    credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),    region: 'eu-central-1'  })    # list buckets in Amazon S3  s3 = Aws::S3::Client.new  resp = s3.list_buckets  S3_BUCKET = resp.buckets[0]  resp.buckets.map(&:name)    S3 = Aws::S3::Resource.new(region: 'eu-central-1')  

Application.html.haml not rendering anywhere

Posted: 09 Dec 2016 07:03 PM PST

I ran into this problem while doing a pinterest clone in Ruby on Rails (https://www.youtube.com/watch?v=abcnfFS_DS8)

My application.html.haml file isn't rendering, and it seems the only way to edit the homepage is to add to index.html.haml

layouts/_application.html.haml

!!! 5  %html  %head    %title Pin Board    = stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true    = javascript_include_tag 'application', 'data-turbolinks-track' => true    = csrf_meta_tags    %body    %nav.navbar.navbar-default      .container        .navbar-brand= link_to "Pin Board", root_path          - if user_signed_in?          %ul.nav.navbar-nav.navbar-right            %li= link_to "New Pin", new_pin_path            %li= link_to "Account", edit_user_registration_path            %li= link_to "Sign Out", destroy_user_session_path, method: :delete        - else          %ul.nav.navbar-nav.navbar-right            %li= link_to "Sign Up", new_user_registration_path            %li= link_to "Sign In", new_user_session_path    .container      - flash.each do |name, msg|        = content_tag :div, msg, class: "alert alert-info"      = yield  

//index.html.haml

= link_to "New Pin", new_pin_path  - @pins.each do |pin|    %h2= link_to pin.title, pin  

// What my index looks like

No navbar showing up

// What the tutorial looks like at this point

Mackenzie childs index

If I was to make a guess I would say this is a problem with Bootstrap, or possibly I'm missing some code that connects application.html.haml, or maybe my versions are off?

Rails the best way to scope vars

Posted: 09 Dec 2016 06:20 PM PST

i have a 'Course' model that has the following attributes;

Course    Price - float     Featured - boolean  

My question would be the following, I need 4 lists in my controller, recent courses, paid courses, free courses and featured courses.

It would be good practice to write my controller as follows?

def index    @courses = Course.order(created_at: :desc)      @free_courses = []    @courses.map {|c| @free_courses << c if c.price == 0}      @premium_courses = []    @courses.map {|c| @premium_courses << c if c.price> 0}      @featured_courses = []    @courses.map {|c| @featured_courses << c if c.featured}  end  

Or do the consultations separately?

def index    @courses = Course.order(created_at: :desc)    @free_courses = Course.where("price == 0")    @premium_courses = Course.where("price > 0")    @featured_courses = Course.where(featured: true)  end  

I checked through the logs that the first option is more performance but I am in doubt if it is an anti partner.

Thanks for all!

Split datetime into two separate form fields (RAILS)

Posted: 09 Dec 2016 06:23 PM PST

Question: How do I split datetime into two separate form fields?

I have the following:

<%= f.label :Borrowed, "Check Out Date*" %></td>  <%= f.date_field :Borrowed, :id => "datepicker", min:Date.today, :ignore_time => true, :required => true %></td>    <%= f.label :Borrowed, "Check Out Time*" %>  <%= f.time_field :Borrowed, min:"9:00 AM", max: "4:30 PM", default:"10:00 AM", :ignore_date => true, :required => true%>    <td><%= f.label :Returned, "Check In Date" %>  <td><%= f.date_field :Returned, :id => "datepicker", min:Date.today, :ignore_time => true, :required => true %>    <td><%= f.label :Returned, "Check In Time*" %>  <td><%= f.time_field :Returned, min:"9:00 AM", max: "4:30 PM", default:"10:00 AM", :ignore_date => true, :required => true%>  

So, I have two datetime fields in my database: Borrowed and Returned. I wanted to split up the date and the time so the user could pick a date from a calendar using a jQuery script. (This may be the problem...) What happens is when I fill out and submit the form the time saves correctly, but the date is the same on both Borrowed and Returned.

So in the database it looks like this:

Returned: 2016-12-09 15:00:00 -0800  Borrowed: 2016-12-09 10:00:00 -0800  

jQuery

$('#datepicker').datepicker({format: 'dd/mm/yyyy'});  

Gems

gem 'bootstrap-timepicker-rails'  gem 'bootstrap-datepicker-rails'  

How to edit a page of information and send a request to be updated for a mod?

Posted: 09 Dec 2016 04:21 PM PST

I have a database full of movie information and i would want users to be able to edit that information, but i don't want the information to get updated just yet. I would want a request to be send to a moderator to review it first before anything.

How would i go with something like this? I was thinking of making another column with the edited information so mods can check and update.

  1. So a user would go to /movies/1
  2. User will then see the information and notice that some of the information is outdated.
  3. User clicks on a edit information button and edits the info.
  4. User presses save and it's sent to a column for a mod to check.

Controller test: "ShoppingList.count" didn't change by 1. Expected: 3 Actual: 2

Posted: 10 Dec 2016 02:53 AM PST

I test the controlller "shopping_list". However when I start the test I get this error:

Failure:  ShoppingListsControllerTest#test_should_create_shopping_list [C:/Users/Clemens/meindorfladen/Server/test/controllers/shopping_lists_controller_test.rb:30]:  "ShoppingList.count" didn't change by 1.  Expected: 3    Actual: 2  

So one parameter is missing, but how can this be? Does somebody know the answer? Here is the code: shopping_lists.yml

shopping_list_drogerie:   user: user_heiko   name: Drogerie   created_at: <%= Time.now %>   updated_at: <%= Time.now %>    shopping_list_lebensmittel:   user: user_schmitt   name: Lebensmittel   created_at: <%= Time.now %>   updated_at: <%= Time.now %>  

db/schema

 create_table "shopping_lists", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|      t.integer  "user_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.string   "name"      t.index ["user_id"], name: "index_shopping_lists_on_user_id", using: :btree    end  

models/shopping_list.rb

class ShoppingList < ApplicationRecord    # db associations    belongs_to :user    # if a shopping list is deleted, also delete information about all items on the list    has_many :list_items, :dependent => :destroy    # if a shopping list is deleted, also delete information about who it was shared with    has_many :shared_lists , :dependent => :destroy    has_many :shared_with_users,through: :shared_lists, :source => :user      has_many :invitation    has_one :appointment      # validations    validates :user, :presence => true    validates :name, presence: true, allow_blank: false, uniqueness: {scope: :user_id}  end  

controllers/shopping_lists_controller.rb

class ShoppingListsController < ApplicationController    load_and_authorize_resource      # GET /shopping_lists/1    # GET /shopping_lists/1.json    def show    end      # POST /shopping_lists    # POST /shopping_lists.json    def create      respond_to do |format|        if @shopping_list.save          format.html { redirect_to shopping_list_list_items_path(@shopping_list), alert: 'Shopping list was successfully created.' }          format.json { render :show, status: :created, location: @shopping_list }        else          format.html { render :new }          format.json { render json: @shopping_list.errors, status: :unprocessable_entity }        end      end    end      # PATCH/PUT /shopping_lists/1    # PATCH/PUT /shopping_lists/1.json    def update      respond_to do |format|        if @shopping_list.update(shopping_list_params)          format.html { redirect_to @shopping_list, notice: 'Shopping list was successfully updated.' }          format.json { render :show, status: :ok, location: @shopping_list }        else          format.html { render :edit }          format.json { render json: @shopping_list.errors, status: :unprocessable_entity }        end      end    end      # DELETE /shopping_lists/1    # DELETE /shopping_lists/1.json    def destroy        @shopping_list.destroy        respond_to do |format|          format.html { redirect_to shopping_lists_url, notice: 'Shopping list was successfully destroyed.' }          format.json { head :no_content }        end     end      private      # Use callbacks to share common setup or constraints between actions.      def set_shopping_list        @shopping_list = ShoppingList.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.     private def shopping_list_params        params.require(:shopping_list).permit(:name)     end  end  

EDIT: sorry I forgot the test-controller: shopping_lists_controller_test

require 'test_helper'    class ShoppingListsControllerTest < ActionDispatch::IntegrationTest    include Devise::Test::IntegrationHelpers    include Warden::Test::Helpers      setup do      @drogerieShoppingList = shopping_lists(:shopping_list_drogerie)      @heiko = users(:user_heiko)      @heikoAppointment = appointments(:appointment_heiko)    end      test "should get index" do      login_as(@heiko)      @heiko.confirmed_at = Time.now      get shopping_lists_url      assert_response :success    end      test "should get new" do      login_as(@heiko)      @heiko.confirmed_at = Time.now      get new_shopping_list_url      assert_response :success    end      test "should create shopping_list" do      login_as(@heiko)      @heiko.confirmed_at = Time.now      assert_difference('ShoppingList.count') do        #post shopping_lists_url, params: { shopping_list: @drogerieShoppingList.attributes, user_id:  @heiko.id, appointment: @heikoAppointment }        post shopping_lists_url, params: { shopping_list: @drogerieShoppingList.attributes }      end        assert_redirected_to shopping_list_url(ShoppingList.last)    end      test "should show shopping_list" do      login_as(@heiko)      @heiko.confirmed_at = Time.now      get shopping_list_url(@drogerieShoppingList)      assert_response :success    end      test "should get edit" do      login_as(@heiko)      @heiko.confirmed_at = Time.now      get edit_shopping_list_url(@drogerieShoppingList)      assert_response :success    end      test "should update shopping_list" do      login_as(@heiko)      @heiko.confirmed_at = Time.now      patch shopping_list_url(@drogerieShoppingList), params: { shopping_list: {name: 'WochenendEinkauf'  } }      assert_redirected_to shopping_list_url(@drogerieShoppingList)    end      test "should destroy shopping_list" do      login_as(@heiko)      @heiko.confirmed_at = Time.now      assert_difference('ShoppingList.count', -1) do        delete shopping_list_url(@drogerieShoppingList)      end        assert_redirected_to shopping_lists_url    end  end  

ruby greater than sign getting nomethoderror

Posted: 09 Dec 2016 04:26 PM PST

I wrote the following code in Ruby, but keep getting NoMethodError: undefined method '>' for nil:NilClass. Not sure why it thinks > is a method?

def count_positives_sum_negatives(lst)    pos = 0    neg = 0    for i in 0..lst.length      if lst[i] > 0        pos += 1      elsif lst[i] < 0        neg += 1      end    end    return [pos, neg]  end  

How to skip the name of folder in routes path in Rails?

Posted: 09 Dec 2016 11:34 PM PST

I'm building a frontend part in my rails app. The controllers like posts, comments, etc., will be in a folder I named it public. Therefore, the folders of posts in view is inside public folder as well, but I would like routes come after the root like:

localhost:3000/posts

NOT: localhost:3000/public/posts

It means I would like to skip public folder in routes.

No comments:

Post a Comment