Saturday, September 10, 2016

Building Rails Forms for saving Polymorphic Associations | Fixed issues

Building Rails Forms for saving Polymorphic Associations | Fixed issues


Building Rails Forms for saving Polymorphic Associations

Posted: 10 Sep 2016 08:17 AM PDT

I have categories model which I would like to be able to use with different models. That's how I ended up using Polymorphic with has_many.

With Rails_admin everything works without a problem. But, when I want to create a form by myself, I can't seem to make it save. Here is what I have:

category.rb

class Category < ActiveRecord::Base    has_many :categorizings, inverse_of: :category, dependent: :destroy    has_many :cars, through: :categorizings, :source => :categorizable,           :source_type => 'Car'  end  

categorizing.rb

class Categorizing < ActiveRecord::Base    belongs_to :category    belongs_to :categorizable, :polymorphic => true  end  

car.rb

class Car < ActiveRecord::Base    has_many :categorizings, :as => :categorizable, inverse_of: :car, dependent: :destroy    has_many :categories, through: :categorizings  end  

vendor.rb

class Vendor < ActiveRecord::Base    has_many :categorizings, :as => :categorizable, inverse_of: :vendor, dependent: :destroy    has_many :categories, through: :categorizings  end  

cars_controller.rb

class CarsController < ApplicationController    def new      @car = Car.new    end    def create      @car = current_user.cars.build(car_params)          if @car.save        redirect_to @car          else              render 'new'          end    end    private    def car_params      params.require(:car).permit(:name, :details, :type, :category_ids => [] )    end  end    

This is what I have in the form

<%= f.collection_select :category_ids, Category.all, :id, :name %>  

And I receive this error: Unpermitted parameter: category_ids

I am very confused right now and lost in models. Dont know this is the best approach or not. I would be glad if someone could tell me where I do the mistake.

AJAX delete not working when sending information to rails server

Posted: 10 Sep 2016 08:10 AM PDT

I am trying to make an ajax delete request to my rails backend server but i keep getting an error:

XMLHttpRequest cannot load localhost:3000/teams/1/articles/36/comments/161. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

my ajax request:

handleCommentDelete: function() {  $.ajax({    type: 'delete',    url: 'localhost:3000/teams/' + this.props.team + "/articles/" + this.props.comment.article_id + "/comments/" + this.props.comment.id  }).done(function(response){      console.log(response)  }.bind(this));   },  

im following the correct routing path in rails:

enter image description here

My cors is set up as such:

enter image description here

And my controller:

enter image description here

what i dont get is that error is saying it cant load the url but, type: 'delete' in the ajax call should tell the backend its a delete request shouldn't it?

Nested namespaces in rails error accessing model with same name as namespace

Posted: 10 Sep 2016 08:08 AM PDT

I have a manager and a customer controller. When i want to list all the customers for a specific manager, i used to do it through the manager show action (because it was specific to a manager). So if a customer_id was found a different return value would be generated. But that left we with (sometimes huge) if branches.

Class Api::V1::ManagerController < ApiBaseController     def show        if params.key?[:customer_id]           ....       else           ....       end       render ..., status: 200     end  

To improve my design i introduced additional name spaces for sub resources. So to list all the customers for one specific manager i have a customer controller under the manager name space. There all actions specific to a manager related to a customer resource are going.

 Class Api::V1::Manager::CustomerController < Api:ApiBaseController    def show        Manager.find(params[:id] ...        ...       render ..., status: 200   end  

The routes.rb entry looks now like this

get 'manager/:manager_id/customer' => 'manager/customer#show'  

When testing the new setup i receive now this error

"error":"uninitialized constant Api::V1::Manager::CustomerController::Manager  

When i replace the Manager.find(..) line with another resource it is working, why cann't i access the Manager Resource anymore? I think it has something to do with the name of the namespace, but even renaming the namespace did not help.

Response from Servers... Connection to http://192.168.3.11:3000 refused

Posted: 10 Sep 2016 07:49 AM PDT

Ruby version 2.2.4 Rails version 5.0.0.1 Hello People,

I have programmed an android app, which can take profile pictures from a user. Now I want to upload these profile picture to my Ruby on Rail server. However the upload doesn't work. I receive the Error message:

Response from Servers org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.3.11:3000 refused  

Here is the host-adress I use in my android-app. I use my local ip-adress so this part should be correct.

public class Config {      // File upload url (replace the ip with your server address)    //  public static final String FILE_UPLOAD_URL = "http://192.168.3.11:3000/AndroidFileUpload/fileUpload.php";      public static final String FILE_UPLOAD_URL = "http://192.168.3.11:3000/";      // Directory name to store captured images and videos      public static final String IMAGE_DIRECTORY_NAME = "android_upload";  }  

And this is my ruby on rails app: items_controller

class ItemsController < ApplicationController    before_action :set_item, only: [:show, :edit, :update, :destroy]      # GET /items    # GET /items.json    def index      @items = Item.all    end      # GET /items/1    # GET /items/1.json    def show      send_data(item.file_contents,                type: @item.content_type,                filename: @item.filename)    end      # POST /items    # POST /items.json    def create      @item = Item.new(item_params)        if @item.save        render :show, status: :created, location: @item      else        render json: @item.errors, status: :unprocessable_entity      end    end      # PATCH/PUT /items/1    # PATCH/PUT /items/1.json    def update      if @item.update(item_params)        render :show, status: :ok, location: @item      else        render json: @item.errors, status: :unprocessable_entity      end    end      # DELETE /items/1    # DELETE /items/1.json    def destroy      @item.destroy    end      private      # Use callbacks to share common setup or constraints between actions.      def set_item        @item = Item.find(params[:id])      end        # Never trust parameters from the scary internet, only allow the white list through.      def item_params        params.require(:item).permit(:name, :description, :picture)      end  end  

models/item.rb

class Item < ApplicationRecord    mount_uploader :picture, PictureUploader  end  

uploaders/picture_uploader.rb

class PictureUploader < CarrierWave::Uploader::Base      # Include RMagick or MiniMagick support:    # include CarrierWave::RMagick    # include CarrierWave::MiniMagick      # Choose what kind of storage to use for this uploader:    storage :file    # storage :fog      # Override the directory where uploaded files will be stored.    # This is a sensible default for uploaders that are meant to be mounted:    def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end      # Provide a default URL as a default if there hasn't been a file uploaded:     def default_url      "/images/fallback/" + [version_name, "default.png"].compact.join('_')     end      # Process files as they are uploaded:    # process :scale => [200, 300]    #    # def scale(width, height)    #   # do something    # end      # Create different versions of your uploaded files:    # version :thumb do    #   process :resize_to_fit => [50, 50]    # end      # Add a white list of extensions which are allowed to be uploaded.    # For images you might use something like this:    def extension_white_list      %w(jpg jpeg gif png)    end      # Override the filename of the uploaded files:    # Avoid using model.id or version_name here, see uploader/store.rb for details.    # def filename    #   "something.jpg" if original_filename    # end    end  

routes.rb

Rails.application.routes.draw do    resources :items    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html      # Serve websocket cable requests in-process    # mount ActionCable.server => '/cable'    end  

Did I miss something in my ruby on rails app? How can I send my images from android to Ruby on Rails? Do I need extra software for uploading like a WAMP server? I am totally new to this stuff

Error when trying to open gitignore

Posted: 10 Sep 2016 07:51 AM PDT

I am working on a ruby on rails application. I use the Cloud9 online IDE, which is Ubuntu.

When I go to the root directory, I can't open my .gitignore file. I know I'm in the right spot because when I'm in root and I type ls -la it lists all of my files, including .gitignore

I've seen other threads and some suggest using either open or see, followed by .gitignore. And they always work for OP. But neither of them work for me.

I tried this one:

open .gitignore`  

But when I use that, I get the following error:

Couldn't get a file descriptor referring to the console  

And when I use this command:

see .gitignore  

I get the following error:

Warning: unknown mime-type for ".gitignore" -- using "application/octet-stream"  Error: no "view" mailcap rules found for type "application/octet-stream"  

If anyone has any idea what's going on, please help me out. I can't find any other fix from other threads, other than using the two commands above.

omniauth-facebook+devise callback does not get executed

Posted: 10 Sep 2016 06:49 AM PDT

I have implemented devise and omniauth-facebook following the instructions below:

https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

Problem

My "facebook" callback function does get called.

If I uncomment the "facebook" function, error occurs. Routing seems to be working fine

However, the code inside the function does not seem to be executed.

The following code does not raise any error.

I have been looking in to this problem for days. Please help...

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController        def facebook      raise params.inspect    end      def failure      redirect_to root_path    end    end  

Log

Finished "/cable/" [WebSocket] for ::1 at 2016-09-10 22:32:32 +0900  MessagesChannel stopped streaming from messages  Started GET "/cable" for ::1 at 2016-09-10 22:32:32 +0900  Started GET "/cable/" [WebSocket] for ::1 at 2016-09-10 22:32:32 +0900  Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)  MessagesChannel is transmitting the subscription confirmation  MessagesChannel is streaming from messages  Started GET "/users/auth/facebook" for ::1 at 2016-09-10 22:32:34 +0900  I, [2016-09-10T22:32:34.770050 #84008]  INFO -- omniauth: (facebook) Request phase initiated.  Started GET "/users/auth/facebook" for ::1 at 2016-09-10 22:32:34 +0900  I, [2016-09-10T22:32:34.994734 #84008]  INFO -- omniauth: (facebook) Request phase initiated.  Finished "/cable/" [WebSocket] for ::1 at 2016-09-10 22:32:35 +0900  MessagesChannel stopped streaming from messages  Started GET "/users/auth/facebook/callback?code=AQBICSjBfjCN7rGbCZLSkdg25FqTZGsnDrJi1UhBj0RwSQBjuZ5bTxEA025jApkwWiianigtILjRV5Uv067Yg73MGzi7sB5BT9yU0kjm7wzYzkBhWMmT0Aecw4ajACkSbBNfVUIii0cokommOAbSJgbzmfKRgbMGmdgYZsF6rBDuPyAGHnFgAa6bSl3jUmzW25SCTY9CDARiGlr880B-gwMs3gX0_KbtXnygAkBhNHoBSFFOIIY7w4QIMQHzZe1aLz6VWz_LxnuN88Ao8_lWOLPCfxsOWUJkdjYbLCowXmu1bpOu1zUuXSf6Dw9qBnWm73XvMyMD3iSasRRqlFW1uVde&state=2362c719c103b6b19f053ccc31b0b90ab34d137a71c2cb8d" for ::1 at 2016-09-10 22:32:40 +0900  I, [2016-09-10T22:32:40.549353 #84008]  INFO -- omniauth: (facebook) Callback phase initiated.  Processing by Users::OmniauthCallbacksController#facebook as HTML    Parameters: {"code"=>"AQBICSjBfjCN7rGbCZLSkdg25FqTZGsnDrJi1UhBj0RwSQBjuZ5bTxEA025jApkwWiianigtILjRV5Uv067Yg73MGzi7sB5BT9yU0kjm7wzYzkBhWMmT0Aecw4ajACkSbBNfVUIii0cokommOAbSJgbzmfKRgbMGmdgYZsF6rBDuPyAGHnFgAa6bSl3jUmzW25SCTY9CDARiGlr880B-gwMs3gX0_KbtXnygAkBhNHoBSFFOIIY7w4QIMQHzZe1aLz6VWz_LxnuN88Ao8_lWOLPCfxsOWUJkdjYbLCowXmu1bpOu1zUuXSf6Dw9qBnWm73XvMyMD3iSasRRqlFW1uVde", "state"=>"2362c719c103b6b19f053ccc31b0b90ab34d137a71c2cb8d"}  Redirected to http://localhost:3000/  Filter chain halted as :authenticate_user! rendered or redirected  Completed 302 Found in 1ms (ActiveRecord: 0.0ms)  

Versions

devise 4.2.0  omniauth 1.3.1  omniauth-oauth2 1.4.0  omniauth-facebook 4.0.0  rails 5.0.0.1  

Rails 5 - sending data from controller to javascript in json format [on hold]

Posted: 10 Sep 2016 06:45 AM PDT

I want to be able to send an array of object to my Google Maps, so I can display the locations.

What I want to ask is what is the best way to do it? I was trying to use RABL gem but the tutorials they have are not exactly up to date.

Then I found info about building and API using rails. This seems like a good plan, but I have no idea how to use it. Google is filled with tuts but only for building API-only app, and I already have my app and just want to add an API to it.

Where should I start looking for it?

No route matches [GET] "/contato"

Posted: 10 Sep 2016 06:42 AM PDT

I'd like to do a contact form, but I'm get a routing error.

No route matches [GET] "/contato"  

My view (contato.html.erb):

<%= form_tag(contato_path, method: :post) %>                    <div class="row">          <div class="col-md-12">              <%= text_field_tag 'name', placeholder: "Name", class: "form-control" %>          </div>      </div>        <div class="row">          <%= submit_tag 'Send' %>          </div>    <% end %>  

My controller (pages_controller.erb):

class PagesController < ApplicationController

  def home      .....    end      def search     .....    end      def contato      .....    end  end  

Routes:

post '/contato' => 'pages#contato'  

Rake routes:

contato_path    POST    /contato(.:format)  pages#contato  

find events within date range of search results in rails/ruby

Posted: 10 Sep 2016 07:24 AM PDT

I'm struggling a bit to get this to work, I have a working search function on my website using searchkick.

However i'm wanting to allow my users to filter the results on the results page.

This is my controller for reference:

def search      @events = Event.page(params[:page]).per(10).search(params[:search], misspellings: { distance: 1 }, order: { date: :asc, eventname: :asc }, match: :word_start, page: params[:page], per_page: 20)      if @events.results.any?        render 'events/results'      else        @popevents = Event.limit(3).order('RANDOM()')        render 'events/noresults'      end    end  

Now what i'm wanting is a simple date picker in the view, that allows the users to search a date range (to and from) of the events returned then on submit it would return only the events in that range. I've looked at filterrific but got confused and wasnt sure thats what i actually need?

Any help would be much appreciated!

edit

So if i have this:

<label for="datefrom">Date From:</label>        <input type="date" id="datefrom" class="form-control" name="datefrom" value="dd/mm/yyyy">        <label for="dateto">Date To:</label>        <input type="date" id="dateto" class="form-control" name="dateto" value="dd/mm/yyyy">    <div style="float:right">          <button class="btn btn-info" name="button">Apply Filters</button>        </div>  

I'm wondering what i need to put on the button, And also would the bit in the controller go into the if @events.results.any? section?

Thanks

Rails link_to polymorphic parent, which can have a nested route

Posted: 10 Sep 2016 07:15 AM PDT

I have the Comment model, which is polymorphic associated to commentable models like Project, User, Update etc. And I have a page where a user can see every User's comment. I want a link near each comment with an address of an object this comment is associated with. I could write something like that:

link_to 'show on page', Object.const_get(c.commentable_type).find(c.commentable_id)  

But this will work only for not nested routes (like User). Here's how my routes look like:

resources :users do    resources :projects, only: [:show, :edit, :update, :destroy]  end  

So when I need a link to a Project page, I will get an error, because I need a link like user_project_path. How can I make Rails to generate a proper link? Somehow I have to find out if this object's route is nested or not and find a parent route for nested ones

Rails - scope for records where not in join table

Posted: 10 Sep 2016 06:07 AM PDT

I have two models - Tournament and Player associated through a join table:

class Tournament < ApplicationRecord      has_many :tournament_players    has_many :players, through: :tournament_players    end      class Player < ApplicationRecord      has_many :tournament_players    has_many :tournaments, through: :tournament_players      scope :selected, -> (tournament) { includes(:tournaments).where(tournaments: {id: tournament.id}) }    end  

I have lots of Tournaments, and each one can have lots of Players. Players can play in lots of Tournaments. The scope

scope :selected, -> (tournament) { includes(:tournaments).where(tournaments: {id: tournament.id}) }  

successfuly finds all the players already added to a tournament, given that tournament as an argument.

What I'd like is a scope that does the opposite - returns all the players not yet added to a given tournament. I've tried

scope :not_selected, -> (tournament) { includes(:tournaments).where.not(tournaments: {id: tournament.id}) }  

but that returns all the players.

I've tried the suggestions on this question - using scope :not_selected, -> (tournament) { includes(:tournaments).where(tournaments: {id: nil}) } - but that doesn't seem to work - it just returns an empty array.

After changing from sqlite to postgres (rails) destroy and edit are not working for my projects

Posted: 10 Sep 2016 07:41 AM PDT

So I am making a website(portfolio) for my projects, wich has Projects, Contact, and a Devlog, in order for people to be able to follow my work and progress, but when I changed to postgres deployed to heroku somehow edit and destoy are no longer working.

Errors I am guetting

EDIT:

PG::DatatypeMismatch: ERROR: argument of WHERE must be type boolean, not type integer LINE 1: SELECT "posts".* FROM "posts" WHERE (1) LIMIT 1 ^ : SELECT "posts".* FROM "posts" WHERE (1) LIMIT 1  

DESTROY:

No route matches [POST] "/posts/1"  

This one appearently is trying to delete the posts (wich are my devlogs)

This is my Index of projects

    <!DOCTYPE html>  <html>      <head>          <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,400italic,700,600' rel='stylesheet' type='text/css'>          <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">          <meta charset="utf-8">          <title>Marcos Collado - Graphic Designer/FrontEnd dev</title>      </head>      <body>          <div class="selector_container">                  <%= image_tag("web.svg",:alt => "web",:id => 'web') %>                  <%= image_tag("logo.png",:alt => "logoSolstice",:id => 'logo') %>                  <%= image_tag("logo.png",:alt => "logoSolstice",:id => 'logo') %>            </div>            <h1 class=title>Projects</h1>              <div id="project_wrap" class="skiny_wrap">                  <% @projects.each do |project|  %>                          <div class="post">                              <h2 class="name"><%= project.name %> </h2>                              <p class="description"><%= project.description %> </p>                                <% if project.has_photo? %>                                          <a href="projects/<%=project.id%>">                                              <div class="img_container" style="background-image: url(/photo_store/<%=project.id%>.<%=project.extension%>)"></div>                                          </a>                              <%else%>                                  <p> theres no image in here </p>                              <%end%>                                <p class="category"><%= project.category %> </p>                              <p class="date"><%= project.created_at.strftime('%A, %B %d') %> </p>                              <hr>                          </div>                  <%end%>                </div>        </body>  </html>  

This is my "show"

<div id="contact_wrap" class="skiny_wrap">      <br><br>    <h2><%=@project.name%></h2>  <br>  <div class="focus_photo">    </div>  <%=@project.link%>  <br><br>  <div class="focus_photo">    </div>  <%=@project.description%>  <br><br>  Theme: <%=@project.category%>  <br><br>  <div class="focus_photo">    </div>    <%= link_to "Edit", edit_post_path(@project) %>  <%= link_to "Delete", post_path(@project), method: :delete, data:{ } %>    </div>  

And this is my controller for projects

class ProjectsController < ApplicationController      before_action :find_project, only: [:show,:edit,:update,:destroy]      has_scope :by_category, type: :array        def index        @projects = apply_scopes(Project).all        @project = Project.new      end        def new        @project = Project.new      end        def create        @project = Project.new project_params          if @project.save              redirect_to @project, notice:"Everything went allright, no need to worry"          else              render 'new', notice: "Oh no, How could we Screw up?!"          end      end        def show        @project = Project.find(params[:id])        unless @project          render json: {error: "The project you are looking for doesn't seem to exist"},          status: 404          return        end      end        def update          if @project.update project_params              redirect_to @project, notice: "we have an update working"          else              render 'edit'          end      end        def destroy        @project.destroy        redirect_to projects_path      end        private        def find_project          @project = Project.find(params[:id])      end        def project_params          params.require(:project).permit(:name, :description, :link, :category, :photo)      end    end  

I do not know if you need anything else, to help me out, but please ask if the info is needed.

What does yield inside a controller action do?

Posted: 10 Sep 2016 05:13 AM PDT

I was looking through the Devise code and noticed that most of the controllers yield the resource being created.

class Devise::RegistrationsController < DeviseController    # ...    def create      build_resource(sign_up_params)        resource.save      yield resource if block_given?      # ...  

This must be some sort of extendability feature but I don't really get how you would pass a block to to the controller action?

Note: This question is about how you would actually do in the Rails request cycle, not about how blocks in Ruby work.

RAILS Auto refresh partial

Posted: 10 Sep 2016 06:06 AM PDT

I have a controller events with action show :

  def show      @event = Event.get(params[:id])        if !connected? || !@event         return redirect_to request.referrer || root_path      end        @requests = @event.get_requests    end  

In view show.html.erb i have

<script>    $(document).ready(       function() {        setInterval(function() {          $('#requests').load('/events/reload_requests');      }, 2000);    });  </script>  ...  <div class="party-block" id="requests">      <%= render partial: 'requests' %>  </div>  ...  

The javascript function call controller method events/reload_requests :

def reload_requests    @requests = @event.get_requests    render partial: 'events/requests'  end  

And content of partial _requests.html.erb :

<%= Time.now %>  <h4><%= t '.requests' %></h4>  <% @requests.each do |r| %>   <span class="request">   ...  <% end %>  

Problem : The javascript function load all the content of my show.html.erb page in div #requests, but in the copy of show.html.erb in the div, it refresh div #request correctly : enter image description here You can see, in show#requests i have the content of show. Than you

Review Reputation System

Posted: 10 Sep 2016 04:53 AM PDT

I am trying to integrate review reputation to my existing rails application. A user can leave a review to a model with start rating by category, review title, review body, and with photos along; examples similarly to Amazon Customer Reviews, Airbnb Host Reviews or Shop Oreilly customer reviews. Moreover, I figured out there is 'Was this review helpful for you?' for a review. I also want to have this along with each review in my application. Yet, I only found Twitter ActiveRecord Reputation System which I am not so sure how I can achieve my goal by using it according to my requirements.

Does anybody here have experience with such review reputation system using Ruby on Rails? Please help share your ideas and experience below. I appreciate your help in advance.

ActiveView::Template::Error ( uninitialized constant CustomBreadcrumbsBuilder )

Posted: 10 Sep 2016 03:55 AM PDT

I'm using a gem called breadcrumbs_on_rails, and in order to use a view for this gem, I have created a class named: CustomBreadcrumbsBuilder in my lib/ directory as fellows:

class CustomBreadcrumbsBuilder < BreadcrumbsOnRails::Breadcrumbs::Builder    def render      @context.render "/layouts/breadcrumbs", elements: @elements    end  end  

And I'm using this class in application.html.haml file to render the very layout in the following way:

%main    = render_breadcrumbs builder: ::CustomBreadcrumbsBuilder  

It successfully loads the file in development environment, but in production, it's producing the following error:

ActionView::Template::Error (uninitialized constant CustomBreadcrumbsBuilder):  

I have tried the following things:

Added following to my config/application.rb:

config.autoload_paths += %W(#{config.root}/lib/)  

And

config.autoload_paths << "#{Rails.root}/lib"  

But none of thing is working. Again, it is working in development mode, but fails in production.

I'm using Rails 5.0.0, and ruby 2.2.3, and on production, I'm using Puma and Nginx to serve the requests.

How do I delete images of some versions on carrierwave?

Posted: 10 Sep 2016 03:39 AM PDT

I use carrierwave. Recently I figured out how to recreate other visions using recreate_versions! something like this

Model.all.each do |model|      model.image.recreate_versions!  end  

But I realized this method just creates new versions, it does not delete previous version's images.

Is there method that deletes images that version do not exist?

Psych::SyntaxError: (<unknown>): found character that cannot start any token while scanning for the next token at line 34 column 4

Posted: 10 Sep 2016 04:00 AM PDT

I am geeting Below Error when trying to find the particular record and i have also used serialize :value

2.0.0-p598 :003 > Model.find(123)

from /home/linux3/.rvm/rubies/ruby-2.0.0-p598/lib/ruby/2.0.0/psych.rb:205:in parse' from /home/linux3/.rvm/rubies/ruby-2.0.0-p598/lib/ruby/2.0.0/psych.rb:205:inparse_stream' from /home/linux3/.rvm/rubies/ruby-2.0.0-p598/lib/ruby/2.0.0/psych.rb:153:in parse' from /home/linux3/.rvm/rubies/ruby-2.0.0-p598/lib/ruby/2.0.0/psych.rb:129:inload' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/coders/yaml_column.rb:26:in load' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/attribute_methods/serialization.rb:105:inunserialize' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/attribute_methods/serialization.rb:96:in unserialized_value' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/attribute_methods/serialization.rb:79:intype_cast' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/attribute_methods/read.rb:128:in block in read_attribute' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/attribute_methods/read.rb:111:infetch' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/attribute_methods/read.rb:111:in read_attribute' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/attribute_methods.rb:314:inattribute_for_inspect' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/core.rb:357:in block in inspect' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/core.rb:355:incollect' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/activerecord-4.1.9/lib/active_record/core.rb:355:in inspect' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/railties-4.1.9/lib/rails/commands/console.rb:90:instart' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/railties-4.1.9/lib/rails/commands/console.rb:9:in start' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/railties-4.1.9/lib/rails/commands/commands_tasks.rb:69:inconsole' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/railties-4.1.9/lib/rails/commands/commands_tasks.rb:40:in run_command!' from /home/linux3/.rvm/gems/ruby-2.0.0-p598@tod/gems/railties-4.1.9/lib/rails/commands.rb:17:in' from bin/rails:8:in `require'

Getting count of entries for a sub-model with date filtering in Rails

Posted: 10 Sep 2016 04:36 AM PDT

I want to get count of objects for a sub-model in Rails with date filtering.

Let's explain in detail:

Assume that I have two models.

  • Post
  • Comment

Also the Comment model belongs to Post model

I want to get comments count for each post by date range. For example; I want to get only today's counts.

Does anyone have an idea that how can I do it without many DB queries? Is it possible with counter cache?

Ruby on Rails: Validating rendered HTML with MiniTest

Posted: 10 Sep 2016 03:56 AM PDT

I'm going through the Ruby on Rails Tutorial and I'm surprised that there is no mention of validating the HTML produced.

How does one validate HTML with Rails' MiniTest?

I'm after a local solution, not something which uses W3C's Markup Validation Service - this is too slow if I honour their request for maximum one hit per second.

Rails: Ensure password is present if password_confirmation is given

Posted: 10 Sep 2016 02:32 AM PDT

I'm working through the Ruby on Rails Tutorial and in the exercises for 10.1.2 - Unsuccessful Edits I'm being asked to test that the application correctly catches invalid form submissions.

Perhaps I did the exercise too thoroughly - I've found that it's "valid" to submit a nil password with a non-nil password_confirmation.

I thought that has_secure_password would catch this?

1) Why doesn't it?

2) How do I ensure that if password is equal to password_confirmation?

I currently have: validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

I've tried adding , confirmation: true, but this doesn't help.

Ruby on Rails Scaffolds Community Resource

Posted: 10 Sep 2016 01:38 AM PDT

I'm a noob to rails, and am learning some of its cool features. I'm really impressed by the scaffolds - they seem to be generic frameworks for things like blogs etc.

Is there a community resource where other scaffolds can be found? I'd like, for instance, to create a site that has an image slideshow or similar where a user can log in and upload photos to add to the slideshow and delete existing images or change the order or effects, time etc.

I'm sure that I can amend the Posts scaffold to do something along these lines, like I say I'm a noob at the moment and learning by doing is good, but I see that there is a way of making your own scaffolds, so I wondered if some kind person had made any scaffolds available.

Many thanks...

Ruby on Rails: Cant figure out why my jQuery-ui autocomplete isn't working?

Posted: 10 Sep 2016 03:01 AM PDT

I just followed a youtube tutorial on adding a jQuery-ui autocomplete feature to my search field. This is the link to the tutorial: https://www.youtube.com/watch?v=iMz8HmrQ350.

For some reason it is not working, despite going over the tutorial and rechecking syntax constantly. I'm NOT getting any errors when I reload the web browser, however, nothing appears as a drop down menu as I type in the search field. Interestingly though, if I use an array for sample data, it works (the drop down menu appears with suggestions using the sample array data). But when I try to link it to my database of posts, it no longer works. I have shown example code for both ways below.

My code is below - any help is much appreciated i've been trying to add this feature for a while attempting countless tutorials and methods. It's getting annoying haha.

I am new to coding and have taught myself thus far. Please let me know if any other files are required.

PS. I'm currently using elastic search and search kick for a simple search. Could that possibly have anything to do with the autocomplete feature not working? I'm also using the gem: "gem 'query-ui-rails'" in my gem file incase that is important to know.

posts.coffee

jQuery ->  $('#search').autocomplete      source: "/search_suggestions"  

search_suggestions_controller.rb

class SearchSuggestionsController < ApplicationController        def index          render json: SearchSuggestion.terms_for(params[:term])      end  end  

IF I USE AN ARRAY AS SAMPLE DATA, IT WORKS - EXAMPLE:

 class SearchSuggestionsController < ApplicationController         def index          render json: %w[test test1]       end   end  

MODEL: search_suggestion.rb

class SearchSuggestion < ApplicationRecord        attr_accessible :popularity, :term        def self.terms_for(prefix)          suggestions = where("term like ?", "#{prefix}_%")          suggestions.order("popularity desc").limit(10).pluck(:term)      end        def self.index_posts          Post.find_each do |post|              index_term(post.title)              post.title.split.each { |t| index_term(t) }          end      end        def self.index_term(term)          where(term: term.downcase).first_or_initialize.tap do |suggestion|              suggestion.increment! :popularity          end      end  end  

TASK FILE: search_suggestions.rake

 namespace :search_suggestions do        desc "Generate search suggestions from posts"       task :index => :environment do           SearchSuggestion.index_posts       end  end  

devise-token-auth causing trouble in api namespace

Posted: 10 Sep 2016 12:58 AM PDT

devise-token-auth just works fine when I DONT have the api namespace with controllers nested inside api folder. But if I do, I get the following error

NameError (undefined local variable or method `current_user' for #<Api::LocationsController:0x297f3f0>):    cancancan (1.15.0) lib/cancan/controller_additions.rb:361:in `current_ability'  cancancan (1.15.0) lib/cancan/controller_resource.rb:222:in `current_ability'  cancancan (1.15.0) lib/cancan/controller_resource.rb:80:in `load_collection?'  cancancan (1.15.0) lib/cancan/controller_resource.rb:41:in `load_resource'  ...and many more lines  

However this doesn't seem to happen when I run my server with controllers not nested inside api, and if i move controller file to api folder adding Api:: and changing routes file to this

Rails.application.routes.draw do           constraints :subdomain => 'api' do                           #uncommented during runtime      namespace :api, path: nil, defaults: {format: 'json'} do   #uncommented during runtime        mount_devise_token_auth_for 'User', at: 'auth'        resources :locations      end                                #uncommented during runtime    end                                  #uncommented during runtime  end  

it works like before surprisingly! except I get this error very similar to this SO post after every create though it actually creates a new location as intended. Why does this happen? What explains this strange behaviour? Is spring doing some magic?

NoMethodError (undefined method `location_url' for #<Api::LocationsController:0x56bd2e0>):  app/controllers/api/locations_controller.rb:22:in `create'  

And how to get it working without cancan strangely throwing an error telling that it requires current_user method which seems to vanish if I put my contollers inside api folder?

How to check if Ajax request was sent in Capybara Rspec?

Posted: 10 Sep 2016 12:52 AM PDT

I have a search interface with instant search as you type. It is optimized to send AJAX requests only when they are needed, so I want to test if it does it correctly.

How do I check if Ajax request was sent? (any request would be good enough) .. also would be good to check if Ajax request was aborted (in other testcase)

How should i add header to HTTP GET request using ruby

Posted: 10 Sep 2016 03:35 AM PDT

Trying to add header in the request

email = "blahblah@gmail.com"  token = "abcdefghijk"  url = "http://www.somewebsite.com/request?params1=value1&params2=value2"    uri = URI.parse(url)  http = Net::HTTP.new(uri.host, uri.port).start  request = Net::HTTP::Get.new(uri.request_uri)  request['email'] = email  request['token'] = token    response = http.request(request)    render json: response.body  

The results i have gotten back is {"error":"invalid request parameters"}

I am supposed to get back a list of data in json. I tried using postman to test if the url is working and passed the email and token inside header and i got back the data that i wanted. I am not sure where it went wrong with the code. Can anybody advise me which part did i do wrongly? Thanks a lot!

Which type of token auth is more secure for api?

Posted: 10 Sep 2016 12:28 AM PDT

I am confused if I should choose between devise-token-auth (issues new tokens for each request) or knock (issues a json web token once and keeps using it till it expires or user signs in again)

  1. Timing Attacks: While one might say token authentication is vulnerable to timing attacks, their docs say they are securely comparing the tokens mitigating timing attacks as mentioned in this gist. Is it still flawed?

  2. Network Failures: Is there an advantage in issuing tokens for every request? And what happens if network failures like the one mentioned in here happen?

  3. Stealing Tokens: If something like knock-JWT is used, what happens when someone somehow (by intercepting in HTTP or even with HTTPS enabled using client side apps/extenstions to capture outgoing request headers) steals the token? Can they use it and get responses as given originally to that user? Does the same happen when someone somehow steals a token issued by devise-token-auth? (It doesn't make it harder because they can't keep using the token again: making a request using a stolen token help get new tokens, hence can infinitely be in contact with server, however, both of them canNOT be in contact, only one can while the token held by other is unusable - is this an advantage or disadvantage?)

Is continuously issuing tokens possible in case of JWT and is it worth doing it? (Like making the server issue a new token with a new expiry after each request)

PS: I just came across these two libs for Rails for effectively managing tokens integrating with devise. If there's a better one - which typically one would use for ecommerce like APIs - I'm open to using that.

How to use TCPServer in Ruby on Rails?

Posted: 09 Sep 2016 11:38 PM PDT

I am using Ruby on Rails on Cloud9 IDE

$ ruby -v  ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]   $ rails -v  Rails 4.2.4  

I have to transmit data between server and GPS device. I put on device and did code like below.

My_Controller

class DashboardController < ApplicationController        before_action :authenticate_user!             def index            require 'socket'          server = TCPServer.new ("127.0.0.1",8000)          loop do            Thread.start(server.accept) do |client|              client.puts "Hello !"              client.puts "Time is #{Time.now}"              client.close            end          end          @bookings = Booking.where(user: current_user).joins(:customer, :driver, :car)          @customers = Customer.where(user: current_user)         end  end` ****   

when i ran this i got

<html>    <head>      <meta charset='utf-8'>       <title>Error 502 - Bad Gateway</title>      <link rel="stylesheet" type="text/css" href="https://cdn.c9.io/errors/style.css" />      <style type="text/css">      .error_content {          background: rgba(255, 255, 255, 0.23);          padding: 10px;          width: 641px;          margin: 25px 0;          display: none;      }        #error-msg {          display: block;      }      </style>    </head>    <body class="errorUnknown light">      <div id="wrapper">        <h1>Error 502 - Bad Gateway</h1>        <div class="error_content" id="error-msg">            <p>Please click <a href="javascript:location.reload(true)">here</a> to try again, if the issue persists please contact <a href="https://c9.io/support">support</a></p>        </div>          <a href="http://status.c9.io">Status Page</a> |        <a href="https://c9.io/support">Support</a> |        <a href="https://c9.io/dashboard.html">Dashboard</a> |        <a href="https://c9.io">Home</a>      </div>    </body>  </html>  

Kindly, help me how to solve this problem.. Thanks in advance.

give value in rails form's label element in rails

Posted: 09 Sep 2016 11:35 PM PDT

I have a label in my app like below.

<div class = "form-group">    <%= form.label :shipping_destination,:class =>'col-sm-2'%>  </div>  

Now to the label shipping_destination, I want to give a dynamic value coming from spree, which is <%=@order.shipping_address.country.name %>

How do I pass this as a value to the label?

Adding Jquery click handler to dynamically-loaded content

Posted: 10 Sep 2016 01:37 AM PDT

My Rails app loads links to a page dynamically. I want to append an onClick action to those links.

The links are appended to the page properly, but the JS for the page is not being applied to those newly added elements.

I've tried rendering new JS tags to the dynamically-added content. I've also tried including this block of code, which should target any link with .select-link added to the #links div.

        $("#links").on("click", ".select-link", function() {            my code here...          })  

That code works when the links are not dynamically loaded. However, I cannot seem to apply ANY onClick handler to them when dynamically loaded, even in the console.

What could possibly cause this issue?

For more context, the problem I'm trying to solve is here: AJAX-loaded JS not rendering

1 comment:

  1. I am really enjoying reading your well written articles. It looks like you spend a lot of effort and time on your blog. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work.

    senior citizen saving scheme

    ReplyDelete