Sunday, January 8, 2017

Undefined method map on writing to a CSV file in Ruby | Fixed issues

Undefined method map on writing to a CSV file in Ruby | Fixed issues


Undefined method map on writing to a CSV file in Ruby

Posted: 08 Jan 2017 07:34 AM PST

I am trying to write lines from an input form to a CSV file from a string in a Rails model:

  def form_to_csv      file = CSV.open('temp.csv', 'w+') do |csv|        self.input_data.split("\n").each do |line|          csv << line        end        input_data_file = InputDataFile.new(file: file)      self.input_data_file = input_data_file      end  

However I get the error:

undefined method `map' for "...":String Did you mean? tap

Any ideas welcome.

Ruby on Rails update_attibutes not working

Posted: 08 Jan 2017 07:19 AM PST

I am trying to set an user as admin, the method is:

def set_user_admin      if admin_true? == true        user = User.find(params[:format])        if user == nil          redirect_to managements_path        else          user.update_attributes(admin: true, assistant: true,             businessman: true)          redirect_to managements_path          flash[:notice] = "The user #{user.name} is an admin user now"        end      else      end    end  

The method run just fine, but is not saving in data base. Some validation is stopping the action. Then I run the command in terminal:

u = User.find_by_id(3)  u.update_attributes(admin: true)  (0.1ms)  rollback transaction  => false  u.errors  @messages={:password=>["Choose a password", "Your password must be at least 4 characters  "], :password_confirmation=>["You must confirm your password  "]}  

So, I can't update user as admin because the password validations are called in the action.

Does anyone know why password and update_password validation is being called in update_attributes? I do not understand why

How to hide "Failed to load resource: the server responded with a status of 403"?

Posted: 08 Jan 2017 07:12 AM PST

I have error Failed to load resource: the server responded with a status of 403 in browser console. How can I hide it? It is Ruby on Rails project and some urls for images are expired

Spree_auth_devise: how to add create.js.erb file?

Posted: 08 Jan 2017 07:04 AM PST

I have modal form to sign-in:

= form_for(Spree::User.new, :url => spree.create_new_session_path, :as => :spree_user, html:{id: 'log_in_user', :'data-type' => 'json'}, remote: true) do |f|    = f.email_field :email, :class => 'form-control', :tabindex => 1, :placeholder => Spree.t(:email)    = f.password_field :password, :class => 'form-control', :tabindex => 2, :placeholder => Spree.t(:password)    = f.submit 'Submit', :tabindex => 3, :class => 'btn btn-lg btn-success btn-blue'  

and some js into my welcome.js

$("form#log_in_user, form#register_user").bind("ajax:success", function(event, xhr, settings) {      $(this).parents('.modal').modal('hide');    })  

It works fine, but i want to reload partial 'login-bar'

I tried to create user_sessions/create.js.erb

alert('123');  $(".user-area").load("<%= j render partial: 'shared/login_bar' %>");  

But it doesn't work. So i can't undestand how spree_auth_devise views works, where and how i can override them and add my own js.erb files. Any help?

Rails Paperclip for both PDF and Image?

Posted: 08 Jan 2017 06:54 AM PST

I wanted to make user able to upload either PDF or image . I know only for handling image is there anyway to handle both image and pdf?

I can do up to here

Inside Post Model:

  has_attached_file :image    validates_attachment_content_type :image, :content_type => {:content_type => %w(image/jpeg image/jpg image/png application/pdf application/msword application/vnd.openxmlformats-officedocument.wordprocessingml.document)}  

In console:

bin/rails g paperclip post attachment  

If it is image then i can do this in view

=image_tag post.image.url(:medium)    # It is haml syntax  

But how do i display download link if it is pdf or let say word file?

query polymorphic models for model / user inclusion

Posted: 08 Jan 2017 06:41 AM PST

How can I check the rails way with polymorphic models whether a model instance is included or not? I have a notification class that is polymorphic and would like to check whether a certain model instance has a user who wants to be notified and whether a user has subscribed to a certain model instance.

class Notification < ApplicationRecord    belongs_to :user    belongs_to :notifyable, polymorphic: true  end    class User < ApplicationRecord    has_many :user_projects    has_many :projects, through: :user_projects    has_many :notifications, as: :notifyable    belongs_to :organisation  end    class Screen < ApplicationRecord    belongs_to :app    has_many :display_fields    has_many :notifications, as: :notifyable  end  

Why is the pdf I'm extracting from Word via office.js corrupted?

Posted: 08 Jan 2017 05:46 AM PST

I'm using the demo code (mostly) found here to pull a pdf out of a word document on Office365.

When I send the file to a basic ruby controller (that just saves it to a tmp file so I can examine it), I'm able to open the pdf, but all the pages are blank. I tried encoding / decoding to base64 but then it was unopenable.

Here is the salient JS code, what executes once I have all the slices of the file stored in the docdataSlices array:

What am I missing? Any help mucho appreciated.

function onGotAllSlices(docdataSlices) {    var request = new XMLHttpRequest();    var docdata = [];    for (var i = 0; i < docdataSlices.length; i++) {      docdata = docdata.concat(docdataSlices[i]);    }      var fileContent = new String();    for (var j = 0; j < docdata.length; j++) {      //fileContent += String.fromCharCode(docdata[j]);      // base 64 encode      fileContent += window.btoa(docdata[j]);    }      // Now all the file content is stored in 'fileContent' variable,    // you can do something with it, such as print, fax...      // Send the file as the body of an HTTP POST    // request to the web server.    request.open("POST", "http://127.0.0.1:3000/files");    request.send(fileContent);      console.log('got the whole file!');  }  

And here is the code in my vanilla rails controller to simply save the file:

require 'base64'    class FilesController < ApplicationController      def create      decoded_base64_content = Base64.decode64(request.body.read)      tmp_file = "#{Rails.root}/tmp/addin.pdf"      File.open(tmp_file, 'wb') do |f|        f.write decoded_base64_content      end      render :nothing => true    end  end  

Ruby on Rails, 3 tables' has_many associations between each through one table

Posted: 08 Jan 2017 05:09 AM PST

I have 3 Models (Result, Player, Game), that have many-to-many assoctiations between each others through (GameResult)

class Result < ApplicationRecord     has_many :games, :through => :game_results     has_many :players, :through => :game_results     has_many :game_results      validates :score, presence: true      validates :time, presence: true  end    class Player < ApplicationRecord     belongs_to :user     has_many :games, :through => :game_results     has_many :results, :through => :game_results     has_many :game_results, dependent: :destroy     validates :firstname, presence: true, length: { minimum: 3, maximum: 88 }     validates :lastname, presence: true, length: { minimum: 3, maximum: 88 }     validates :user_id, presence: true       def fullname         "#{firstname} #{lastname}"     end  end    class Game < ApplicationRecord     has_many :results, :through => :game_results     has_many :players, :through => :game_results     has_many :game_results     validates :title, presence: true, length: { minimum: 3, maximum: 50 }     validates_uniqueness_of :title  end      class GameResult < ApplicationRecord     belongs_to :result     belongs_to :game     belongs_to :player       validates :result, presence: true     validates :game, presence: true     validates :player, presence: true  end  

And my form to create new Result looks like this:

<%= form_for(@result, :html => {class: "az-form", role: "form"}) do |f| %>            <%= f.label :score, class: "az-form__label" %> <br/>          <%= f.number_field :score, step: :any, class: "az-form__input", placeholder: "Firstname of player", autofocus: true %>            <%= f.label :time, class: "az-form__label" %> </br>          <%= f.number_field :time, step: :any, class: "az-form__input", placeholder: "Lastname of player" %>            <div class="text-center">              <%= f.collection_select :player_ids, Player.all, :id, :fullname, {}, {multiple: true} %>              <%= f.collection_select :game_ids, Game.all, :id, :title, {}, {multiple: true} %>          </div>            <div class="text-center">              <%= button_tag(type: "submit", class: "az-form__submit") do %>                  <%= f.object.new_record? ? "Create player" : "Update player" %>              <% end %>          </div>        <% end %>    

Problem is in my error preventing to create Result that saying 'Game result is invalid', so my quesion is: its even possible to create table that contain 3 ids of different table and submit for this table in one form, actually im newbee in rails and i dont know how to create action for this kindy staff, for now create action for Results controller looks like this

def create  @result = Result.new(result_params)    respond_to do |format|    if @result.save      format.html { redirect_to @result }      flash[:success] = "Result was successfully created"      format.json { render :show, status: :created, location: @result }    else      format.html { render :new }      format.json { render json: @result.errors, status: :unprocessable_entity }    end  end  end  

and params

def result_params    params.require(:result).permit(:score, :time, player_ids: [], game_ids: [])  end  

Undefined method `log_in' in Ruby on rails

Posted: 08 Jan 2017 04:44 AM PST

I'm currently working through Chapter 8 of Michael Hartl's Ruby on Rails tutorial.

In section 8.2.1 The log_in method I'm getting an NoMethodError in SessionsController#create when calling log_in user. It's almost identical to this linked issue but I'm still stuck and I can't see why.

My Current Code


class SessionsController < ApplicationController    def create      user = User.find_by(email: params[:session][:email].downcase)      if user && user.authenticate(params[:session][:password])        log_in user        redirect_to user      else        flash.now[:danger] = 'Invalid email/password combination'        render 'new'      end    end   end  

class ApplicationController < ActionController::Base    protect_from_forgery with: :exception    include SessionsHelper  end  

module SessionsHelper    def log_in(user)      session[:user_id] = user.id    end  end  

I can get it to work if I move log_in into SessionsController but I can't figure out why the controller can't use the method when it's in SessionsHelper. I've restarted my rails server and made sure everything is saved. I must of overlooked something but I can't see it myself.

Any ideas?

Can't get HTTP GET params Rails 5 API on production stage (AWS elasticbeanstalk)

Posted: 08 Jan 2017 04:26 AM PST

I have rails 5 API. Tested on my local it running perfect. But after deploy to elastic beanstalk I have problem, I can't getting HTTP GET parameters :

http://example.com/customers?token=11111  

When get using params[:token] there no value.

Is there related with nginx config or something ?

Eager-load for custom joins in ActiveRecord

Posted: 08 Jan 2017 06:24 AM PST

I have a table of restaurants that have many reservations. Now I would like to query all restaurants and in case they have reservations for 2 people it should preload these associations. In case there are no reservations for 2 it should still return the restaurants, but with an empty association.

For that I tried the following query:

Restaurant.eager_load(:reservations).where("number_of_people = ?", 2)  

However, this doesn't work, since it discards all restaurants that do have reservations but none of them is for 2 people.

So what I would like to do is moving that condition into the join condition. Something like:

Restaurant.joins('LEFT OUTER JOIN \"reservations\" ON \"reservations\".\"restaurant_id\" = \"restaurants\".\"id\" AND \"reservations\".\"number_of_people\" = ?', 2)  

That would give the result I need, however this is not preloading the "reservations" associations but causing an N+1 issue.

It doesn't seem like eager_load accepts custom queries. I found these threads: https://github.com/rails/rails/issues/12270 and JOIN ON ... AND conditions when eager loading association in ActiveRecord but there is no solution offered.

getting syntax error while running rails s -e production

Posted: 08 Jan 2017 05:18 AM PST

After running:

bundle exec rake assets:precompile RAILS_ENV="production"    

I run rails s -e production but I am getting following error and server is not starting.

rails s -e production    => Booting WEBrick  => Rails 4.2.4 application starting in production on http://localhost:3000  => Run `rails server -h` for more startup options  => Ctrl-C to shutdown server Exiting     C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport4.2.4/lib/active_support/dependencies.rb:274:in `require':  C:/Users/app/models/~$Meeting.rb:1: Invalid char `\x03' in expression (SyntaxError)>         from   C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-  4.2.4/lib/active_support/dependencies.rb:274:in `block in require'from C:/RailsInstaller/Ruby2.2.0/lib/ruby/gems/2.2.0/gems/activesupport-  4.2.4/lib/active_support/dependencies.rb:240:in `load_dependency'  

But running the application on development is working fine.

How to count a column total with relationship in rails

Posted: 08 Jan 2017 03:26 AM PST

I need to count the total amount of a column relationship. I have two tables

people(id(int), infected(boolean)) and inventory(id(int) people_id(int Fk) water(float))  

So I need to know how many waters I have per person whose "infected = true" and how many per person whose infected = false

in rails controller.

thanks for listening

HTTPS Status: 404 Not Found in rails REST api for all routes

Posted: 08 Jan 2017 06:36 AM PST

I am currently developing REST API using rails by following this tutorial http://apionrails.icalialabs.com/book/chapter_two. I am using postman to test the routes but i am getting 404 response code for all actions.

This is my available routes in screentshot

This is the content of my routes file:

Rails.application.routes.draw do       devise_for :users       namespace :api, defaults: { format: :json },              constraints: { subdomain: 'api'}, path: '/' do            resources :users, :only => [:show, :create, :update, :destroy]          resources :sessions, :only => [:create, :destroy]     end  end  

I am using devise for authenticating the user.

Rails Json Builder syntax error, unexpected keyword_end, expecting end-of-input

Posted: 08 Jan 2017 02:26 AM PST

I'm using FullCalendar in my app and feed it with a JSON file for the appointments.

I recently introduced few conditional but this is the error I get when try to load the appointments.json page

index.json.jbuilder:15: syntax error, unexpected keyword_end, expecting end-of-input  

Here is my code to generate the json file with jbuider

json.array! @appointments do |a|  json.ignore_nill!    json.extract! a, :id, :description, :patient_id      if a.patient.blank? && a.description.blank?      json.title "Appuntamento"    end      if a.patient.blank? && a.description.present?      json.title a.description    end      if a.patient.present? && a.description.present?      json.title a.patient.fullname_lastnameFirst + "\n" + a.description.capitalize    end      if a.seat.blank?      json.color "rgb(122, 122, 122)"    else      json.color a.seat.color    end      json.start a.starting_time    json.end a.ending_time    json.url appointment_url(a)    end  

Any idea where it could be the problem with the missing end of input? Thanks already for the help

How to get bar label in Google Timeline chart with Chartkick gem

Posted: 08 Jan 2017 02:22 AM PST

I'm using chartkick gem to render a Google timeline graph. While this works very nicely out of the box, I read on the Google documentation, that I'm also able to include a bar label:

https://developers.google.com/chart/interactive/docs/gallery/timeline#labeling-the-bars

Is there an option to add that extra column to the datatable with the help of Chartkick?

I basically need this to be invoked before the Timeline is rendered:

dataTable.addColumn({ type: 'string', id: 'Name' });

Thanks

ES6 template strings error on Heroku

Posted: 08 Jan 2017 02:08 AM PST

I have some code using template strings which works in development, but the push to Heroku fails with this error:

 ExecJS::RuntimeError: SyntaxError: Unexpected character '`'  

The code is something like this:

`1 + 1 is ${1 + 1}`  

I wonder if the Heroku Node version is too low to support this. I'm not customizing this at all. Just pushing a Rails 4 app with the default configuration.

ActiveAdmin: load and use models from other engine doesn't work

Posted: 08 Jan 2017 01:54 AM PST

I followed the guide in the wiki to use my models from my engine in my main-app with active admin.

The only thing I must change (that doesn't mentioned in the wiki) was this:

if defined?(ActiveAdmin)    ActiveAdmin.register Blog::Category do    end  end  

I just added: Blog::. In my engine "Blog" I added a model named "category" with a name:string attribute. But when I add one in active admin the field name wasn't saved in the database. My request parameters are:

{"utf8"=>"✓", "authenticity_token"=>"PzKDTcoJZ6Sy2tXgw9WSwXiR7aZp81lOtBvfD5Ec3F72H5L7MEMLjlOFgKWQBo2U4n9mPc7AgjcIS3MTIY2nZA==", "category"=>{"name"=>"asdasd"}, "commit"=>"Update Category", "id"=>"1"}  

any ideas why it isn't saved in the databse? When I create a new one, the record is created but without my input.

Heroku deployment data not showing

Posted: 08 Jan 2017 04:53 AM PST

Hello I am making an app which has two model Category and Doctor .. The purpose is to list all doctors .. The app is running perfectly in local server. But when I deploy it to Heroku the data are not showing. Is their any one who can help ?

Create or register ejabberd user from ROR

Posted: 08 Jan 2017 04:18 AM PST

I have installed ejabberd(latest) server on my local machine, there I can register a new user easily from command line and from web http://localhost:5280/admin. Now I want to register a new user from rails(5.0.1). I referred couple of gems like XMPP4R, ruby_bosh but all them lack documentation and example. Please guide me for the same. Thanks for your time and guidance. Please note the project is API only.

Not sure how this code reads

Posted: 08 Jan 2017 12:12 AM PST

I'm browsing github looking at cool code, but don't understand what this code does:

I understand that there are 2 belongs_to associations, but I don't understand what the 'self.request' method means and what it does.

Also, isn't 'transaction' meant for SQL database queries and not ruby code?

Could someone please clarify?

class Friendship < ActiveRecord::Base    belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"    belongs_to :user         def self.request(user, friend)        unless user == friend or Friendship.exists?(user, friend)            transaction do                create(:user => friend, :friend => user, :status => 'requested')                create(:user => user, :friend => friend, :status => 'pending')            end        end    end  

Rails 5: JS treeview from date hash

Posted: 08 Jan 2017 07:29 AM PST

I have model where distinct dates are found and then values are grouped by year, month, day:

def self.tree    dates = MyModel.order("date_trunc('day', datetime_column) DESC")             .distinct.pluck("date_trunc('day', datetime_column)")    hash = Hash.new { |h, y| h[y] = Hash.new { |h2, m| h2[m] = {} } }    dates.each_with_object(hash) do |date, h|      h[date.year][date.strftime('%B')][date.strftime('%b %d')] = date    end  end  

which prints out in view this hash:

{2016=>{"November"=>{"Nov 20"=>Sun, 20 Nov 2016 05:20:00 UTC +00:00}, "December"=>{"Dec 12"=>Mon, 12 Dec 2016 04:05:00 UTC +00:00, "Dec 24"=>Sat, 24 Dec 2016 18:51:33 UTC +00:00, "Dec 30"=>Fri, 30 Dec 2016 06:20:00 UTC +00:00}}, 2017=>{"December"=>{"Dec 12"=>Tue, 12 Dec 2017 15:15:00 UTC +00:00}}}  

In controller I have this:

def update_placements    @placements = #code which finds placements    @treeview = @placements.tree    respond_to do |format|      format.js    end  end  

How do I turn hash above into some nice javascript treeview? For example like here: enter image description here

I'd appreciate any hint where I should be looking at. Thank you!

Addition

In addition I'd need to be able to get records for particular day. Basically it would be opening year, month, day and then populating records for particular day. I was thinking to load year, month, day all together and then for each day records would be loaded separately since table could grow quite big. Records for day would be found buy datetime_column.

Rails4; scope returns ActiveRecord_AssociationRelation not single object

Posted: 07 Jan 2017 11:51 PM PST

I just wonder how I can return one object instead of ActiveRecord_AssociationRelation within models with scope.

For example,

scope :primary, -> { where(is_active: true).last }  

which returns ActiveRecord_AssociationRelation.

So I always have to something like Account.last.credit_cards.primary.last.

How can I achieve this more efficiently?

How should I go about creating an easily maintainable Rails application containing lots of server side logic? [on hold]

Posted: 07 Jan 2017 11:23 PM PST

Work Environment (I have no control over this)
1. Jruby 1.7.12 (Ruby 2.0.0)
2. Rails 4.0.0
3. React.js (little bit)
4. MySQL 5.6
5. Windows 7

I'm asked to convert a Foxpro application to JRuby on Rails. The application will have to read and update database records based on a dozen criteria spread across dozens of tables. The number of records is estimated to be around atleast 50k per table. Will be hosted in a local network and multi-user support is requested (5 to 10 users).

The previous guys that worked on it tried it the Rails way and failed.

What they did
- Created controllers and models.
- Did migrations and stuff.
- Wrote all the application logic inside the controller (Cluttered and confusing)
- Used ActiveRecord to manipulate database tables (Slow)

End Result
- The system runs so slow and sometimes even crashed when RAM filled up. (Maybe from all those behind the scene select queries)

So when I started working on it they asked me to use Sequel raw queries instead of ActiveRecord to be used with the application. Did not have much knowledge on Rails coming from a CPP/Java background, I thought what the hell and immediately started working on it (Bad decision on my part).

What I did
- Created controllers (No more Models since ActiveRecord is not being used)
- No more migrations. (Always knew this wasn't gonna end well)
- Wrote the application logic inside separate Ruby classes (Lets just call them foo_service.rb and foo_dao.rb)
- Sometimes used Sidekiq background jobs for super long tasks.
- MySQL stored procedures are used when needed.
- Progressbar is implemented by updating progress in a MySQL table from Rails as well as from stored procedures and using Ajax calls to fetch it to the front end. (Its probably stupid but it works)

End Result
- The application barely works but feels like an abomination between Java and Rails. To put it simply what I'm doing is calling Ruby scripts through Rails routes.

I want to correct my previous mistakes and do this properly from now on. I'm ready to spend the extra time reverting the previously written code from home if that's what it takes. Any help would be appreciated.

If I'm dealing with a lot of business logic where should I put all those code? And if doing all database table manipulation in Rails is slow how should one go about doing it?

How to disable ActiveRecord query caching that Octopus enforces?

Posted: 08 Jan 2017 02:31 AM PST

I'm using Octopus (latest version) with Rails (latest version) and ActiveAdmin on 2 DBs, one master for writes and one slave for reads. The problem now is, when we add any new DB entry, it is being written to the DB, but it is not being displayed on the index page because the query was cached before we create the new records!

Getting direct messages using Twitter REST api

Posted: 07 Jan 2017 10:58 PM PST

I'm experimenting with twitter REST API with Ruby on Rails.

I'm using twitter gem for the same. I could get the client object using in my code.

client = current_domain.twitter_accounts.first.client

following the documentation given here

The client object works fine. But I couldn't get DirectMessages in the same way.

Also followed this documentation. Here I could not find a way to get DirectMessages. Is there a way in REST API to get twitter direct messages. Or do I need to implement Streaming API.

index.html.erb not getting rendered by rails

Posted: 07 Jan 2017 10:26 PM PST

I am new to Rails and trying to move a web page made using HTML, CSS and Javascript to the rails environment. I have added the third party libraries' stylesheets and javascript to the vendor/assets and the custom javascript and stylesheet to app/assets in the respective javascript and stylesheet folders.

I have defined a route to /home in routes.rb to display this page as:

get '/home', to: 'home#index'  

and the action in the home_controller.rb

class HomeController < ApplicationController    def index      end  end  

I have added my custom HTML page with the styles in index.html.erb

<!DOCTYPE html>  <html lang="en">    <head>    <meta charset="UTF-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>SMS scheduling site</title>      <!--css stylesheets-->    <%= stylesheet_link_tag "jquery-ui.min" %>    <%= stylesheet_link_tag "material.min" %>    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">    <link href='https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&amp;lang=en'          rel='stylesheet' type='text/css'>    <link href='https://fonts.googleapis.com/css?family=Roboto+Mono' rel='stylesheet' type='text/css'>    <%= stylesheet_link_tag "mdDateTimePicker" %>    <%= stylesheet_link_tag "style" %>    </head>    <body>  <div class="container-div">    <!-- Colored FAB button with ripple -->    <button id="fab" class="mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored">      <i class="material-icons">add</i>    </button>      <style>      </style>      <div class="demo-card-wide mdl-card mdl-shadow--2dp">      <div class="mdl-card__title" id="text-div">        <h2 id="title-text" class="mdl-card__title-text">CAMPAIGN</h2>        <br>        <br>        <span id="success">Success!</span>      </div>      <div class="mdl-card__supporting-text">        <form action="#">            <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">            <input class="mdl-textfield__input" type="text" id="campaign-name">            <label class="mdl-textfield__label" for="phone-number-receiver">Campaign Name</label>          </div>            <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">            <input class="mdl-textfield__input" type="text" pattern="-?[0-9]*(\.[0-9]+)?" id="phone-number-receiver">            <label class="mdl-textfield__label" for="phone-number-receiver">Phone Number for recipient</label>            <span class="mdl-textfield__error">Input is not a number!</span>          </div>            <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">            <input class="mdl-textfield__input" type="text" id="start-date">            <label class="mdl-textfield__label" for="start-date" id="start-date-label">Enter start date</label>          </div>              <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">            <input class="mdl-textfield__input" type="text"  id="end-date">            <label class="mdl-textfield__label" for="end-date" id="end-date-label">Enter end date</label>          </div>            <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">            <input class="mdl-textfield__input" type="text"  id="start-time">            <label class="mdl-textfield__label" for="end-date" id="start-time-label">Enter time</label>          </div>            <div class="mdl-textfield mdl-js-textfield less-margin">            <textarea class="mdl-textfield__input" type="text" id="sms-msg" rows="8" columns="40"></textarea>            <label class="mdl-textfield__label" for="sms-msg">Text lines...</label>            </div>          <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">            <input class="mdl-textfield__input" type="text"  id="break-msg" value="1">            <label class="mdl-textfield__label" for="break-msg">Number of Pages</label>          </div>        </form>      </div>    </div>  </div>      <%= javascript_include_tag "jquery-3.0.0.min" %>  <%= javascript_include_tag "jquery-ui.min" %>  <%= javascript_include_tag "material.min" %>  <%= javascript_include_tag "moment.min" %>  <%= javascript_include_tag "draggabilly.pkgd.min" %>  <%= javascript_include_tag "mdDateTimePicker" %>  <%= javascript_include_tag "app" %>  </body>    </html>  

I am getting an error that the HomeController#index is missing a template for this request format. But the view is already defined.

How to fix the error? I suspect it might have something to do with the HTML and CSS code in the view.

Rails doesn't execute create.js via Ajax in native Javacript Vanilla

Posted: 07 Jan 2017 09:23 PM PST

Using Rails 4 and native Javascript (Vanilla). I have the following code to create a Shop record via Ajax. The record creates successfully, but refuses to fire create.js correctly.

Weird behavior is that on Chrome it says Rendered shops/create.js.erb but done nothing, but on Firefox, it says ActionView::MissingTemplate.

I also notice that the request is processed as HTML, if that's the issue.

# shops_controller.rb  class ShopsController < ApplicationController    def create      @day_id = params[:day_id]      shop_details = JSON.parse(shop_params[:shop]).with_indifferent_access      @shop = Shop.find_or_create_by(source_id: shop_details[:shop_id])      @shop.save    end      private      def shop_params      params.permit(        :shop,        :day_id      )    end  end      # global.js  function addShop(dayId, shop) {    var shopJSON = encodeURIComponent(JSON.stringify(shop));    var xhr = new XMLHttpRequest();    xhr.open("POST", "/shops", true);    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");    xhr.setRequestHeader("X-CSRF-Token", CSRF.token());    xhr.send("shop=" + shopJSON + "&day_id=" + dayId);      xhr.onreadystatechange = function () {      if (xhr.readyState == XMLHttpRequest.DONE ) {        if (xhr.status != 200) {          alert('not ok');        }      }    };  }    # app/views/shops/create.js.erb  alert('good');      # Firefox Log    Started POST "/shops" for 127.0.0.1 at 2017-01-08 13:11:36 +0800  Processing by shopsController#create as HTML    Parameters: {"shop"=>"...", "day_id"=>"85"}    Shop Load (0.4ms)  SELECT  `shops`.* FROM `shops` WHERE `shops`.`source_id` = 'ChIJHbeh32U6K4cR-lP5hY96smc' LIMIT 1     (0.2ms)  BEGIN    SQL (3.6ms)  INSERT INTO `shops` (`source_id`, `created_at`, `updated_at`) VALUES ('...', '2017-01-08 05:11:36', '2017-01-08 05:11:36')     (0.8ms)  COMMIT     (0.2ms)  BEGIN     (0.2ms)  COMMIT  Completed 500 Internal Server Error in 34ms (ActiveRecord: 8.1ms)    ActionView::MissingTemplate (Missing template shops/create, application/create with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:    * "/Users/abc/Sites/powerapp/app/views"    * "/Users/abc/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/devise-4.2.0/app/views"  ):    actionview (4.2.6) lib/action_view/path_set.rb:46:in `find'      # Chrome Log:  Started POST "/shops" for 127.0.0.1 at 2017-01-08 13:13:08 +0800  Processing by shopsController#create as */*    Parameters: {"shop"=>"...", "day_id"=>"79"}    Shop Load (0.3ms)  SELECT  `shops`.* FROM `shops` WHERE `shops`.`source_id` = 'ChIJASFVO5VoAIkRGJbQtRWxD7w' LIMIT 1     (0.2ms)  BEGIN    SQL (9.2ms)  INSERT INTO `shops` (`source_id`, `created_at`, `updated_at`) VALUES ('...', '2017-01-08 05:13:08', '2017-01-08 05:13:08')     (0.6ms)  COMMIT     (0.2ms)  BEGIN     (0.2ms)  COMMIT    Rendered shops/create.js.erb (0.8ms)  Completed 200 OK in 44ms (Views: 25.1ms | ActiveRecord: 10.7ms)  

"Completed 204 No Content" response to Ajax request in Rails 5

Posted: 07 Jan 2017 09:11 PM PST

I can't get the controller to send a response to an Ajax request in Rails 5. I have a form with remote:true

</div class='form-control'>    <%= form_tag('api/v1/texts', id: 'text-form', remote:true) do %>      <%= text_area_tag :text, params[:text], :required => 'required', class: 'form-control', id: 'text-area', :rows => 10 %>      <%= submit_tag 'Submit your text', class: 'btn btn-primary btn-lg btn-block' %></div>    <% end %>  </div>  

I have a text.js file

$(document).on("turbolinks:load", function(){    submitTextFormListener();  });    var submitTextFormListener = function(){    $("#text-form").on("ajax:successful", function(event, response){      console.log("Ajax successful")      $("#text-form").append(response);    })      $("#text-form").on("ajax:error", function(event, response){      console.log("Ajax unsuccessful")    })  }  

And I have my controller

class Api::V1::TextsController < ApplicationController    def index      @text = ApiResponse.build_response(params[:text])        respond_to do |format|        format.js {}        render json: @text      end    end  end  

I have tried many different solutions, for example making a partial, but none worked. I'm confused by the fact that there are so many ways to implement ajax that I can't put the pieces together.

I'm trying to get text input from the front end, process it, and then return it as son and print it to the page.

This is the error message:

Started POST "/api/v1/texts" for ::1 at 2017-01-07 21:08:01 -0800  Processing by Api::V1::TextsController#index as JS    Parameters: {"utf8"=>"✓", "text"=>"Inputted text to be processed and returned as json.", "commit"=>"Submit your text"}  No template found for Api::V1::TextsController#index, rendering head :no_content  Completed 204 No Content in 148ms (ActiveRecord: 0.0ms)  

Ruby on Rails - Need Help Optimizing My horrible code involving multiple data models

Posted: 08 Jan 2017 06:34 AM PST

I am working on a personal project and I have hit a wall. I know I am writing bad code and I really wan to refactor the code below. The application has three tables on the same page. Each table contains data from a has-many-though relationship. In essence I have an employees page which contains three tables of employee licenses that all expire in grouped intervals:

ALL EMPLOYEE PAGE

  • Employees with licenses Expiring in 30 days
  • Employees with licenses Expiring in 30-90 days
  • Employees with licenses Expiring in 90 days

All three of these tables are independently paginated and I am allowing the user to enter a search term and search across all three tables.

However I have over 1200 licenses so the page is taking forever to load. How can I optimize this functionality? Any help would be greatly appreciated.

Model

  def self.emp_lic_small     self.all.map{|se| se.employee_licenses.less_than_thirty}.flatten    end      def self.emp_lic_medium      self.all.map{|se| se.employee_licenses.between_thirty_and_ninty}.flatten    end      def self.emp_lic_large      self.all.map{|se| se.employee_licenses.greater_than_ninty}.flatten    end  

Controller

    @small_employee_licenses = SiteEmployee.search(params[:search]).emp_lic_small.paginate(:page => params[:small_lic], :per_page => 20)      @medium_employee_licenses = SiteEmployee.search(params[:search]).emp_lic_medium.paginate(:page => params[:med_lic], :per_page => 20)      @large_employee_licenses = SiteEmployee.search(params[:search]).emp_lic_large.paginate(:page => params[:large_lic], :per_page => 20)  

View

<div class="panel panel-danger">    <div class="panel-heading"><strong>Employee Licenses Expiring in Less Than 30 Days</strong></div>      <table class="table">          <thead>              <th class="text-center">Employee Name</th>              <th class="text-center">Employed By</th>              <th class="text-center">License Name</th>              <th class="text-center">Expiration Date</th>              <th class="text-center">Obtained?</th>              </tr>          </thead>          <tbody>              <% if @small_employee_licenses.present? %>                  <% @small_employee_licenses.each do |e| %>                      <tr>                      <td class="text-center"><%= link_to e.site_employee.to_s, site_employee_path(e.site_employee)%></td>                      <td class="text-center"><%= link_to e.site_employee.site.name, site_path(e.site_employee.site)%></td>                      <td class="text-center"><%= e.license.name %></td>                      <td class="text-center"><%= e.expiration_date.strftime("%m/%d/%Y") %></td>                      <td class="text-center"><%= e.obtained? ? "Yes" : "No" %></td>                      </tr>                      <%end%>              <% else %>                  <tr><td colspan="3">There are currently no Licenses due in the next 30 days.</td></tr>              <% end %>          </tbody>      </table>  </div>  <%= will_paginate @small_employee_licenses, param_name:'small_lic' unless @small_employee_licenses.blank?  %>     <div class="panel panel-warning">    <div class="panel-heading"><strong>Employee Licenses Expiring in 30-90 Days</strong></div>      <table class="table">          <thead>              <th class="text-center">Employee Name</th>              <th class="text-center">Employed By</th>              <th class="text-center">License Name</th>              <th class="text-center">Expiration Date</th>              <th class="text-center">Obtained?</th>              </tr>          </thead>          <tbody>              <% if @medium_employee_licenses.present? %>                  <% @medium_employee_licenses.each do |e| %>                      <tr>                      <td class="text-center"><%= link_to e.site_employee.to_s, site_employee_path(e.site_employee)%></td>                      <td class="text-center"><%= link_to e.site_employee.site.name, site_path(e.site_employee.site)%></td>                      <td class="text-center"><%= e.license.name %></td>                      <td class="text-center"><%= e.expiration_date.strftime("%m/%d/%Y") %></td>                      <td class="text-center"><%= e.obtained? ? "Yes" : "No" %></td>                      </tr>                      <%end%>              <% else %>                  <tr><td colspan="3">There are currently no Licenses due in the next 30 days.</td></tr>              <% end %>          </tbody>      </table>  </div>  <%= will_paginate @medium_employee_licenses, param_name:'med_lic' unless @medium_employee_licenses.blank?  %>   <div class="panel panel-success">    <div class="panel-heading"><strong>Employee Licenses Expiring in 30-90 Days</strong></div>      <table class="table">          <thead>              <th class="text-center">Employee Name</th>              <th class="text-center">Employed By</th>              <th class="text-center">License Name</th>              <th class="text-center">Expiration Date</th>              <th class="text-center">Obtained?</th>              </tr>          </thead>          <tbody>              <% if @large_employee_licenses.present? %>                  <% @large_employee_licenses.each do |e| %>                      <tr>                      <td class="text-center"><%= link_to e.site_employee.to_s, site_employee_path(e.site_employee)%></td>                      <td class="text-center"><%= link_to e.site_employee.site.name, site_path(e.site_employee.site)%></td>                      <td class="text-center"><%= e.license.name %></td>                      <td class="text-center"><%= e.expiration_date.strftime("%m/%d/%Y") %></td>                      <td class="text-center"><%= e.obtained? ? "Yes" : "No" %></td>                      </tr>                      <%end%>              <% else %>                  <tr><td colspan="3">There are currently no Licenses due in the next 30 days.</td></tr>              <% end %>          </tbody>      </table>  </div>  <%= will_paginate @large_employee_licenses, param_name:'large_lic' unless @large_employee_licenses.blank?  %>   

1 comment:

  1. Your blog is in a convincing manner, thanks for sharing such an information with lots of your effort and time
    ruby on rails training
    ruby on rails training India
    ruby on rails training Hyderabad

    ReplyDelete