Tuesday, December 20, 2016

Duplicate delete links | Fixed issues

Duplicate delete links | Fixed issues


Duplicate delete links

Posted: 20 Dec 2016 08:17 AM PST

On a user's profile page, a user can create posts. I've recently added a delete link for users to delete their posts. The problem however, each individual post is showing all delete links for all posts.

Example: So if Jimmy has 3 posts, each post will have 3 delete links

Here's my code:

posts_controller.rb

class PostsController < ApplicationController            def index      @posts = Post.allow      end          def new           @post = Post.new      end            def create          @post = Post.new(post_params)          @post.user_id = current_user.id # assign the post to the user who created it.          respond_to do |f|              if (@post.save)                   f.html { redirect_to "", notice: "Post created!" }              else                  f.html { redirect_to "", notice: "Error: Post Not Saved." }              end          end      end            def destroy # users can delete their own posts      @post = Post.find(params[:id])      if current_user == @post.user          @post.destroy      end      redirect_to root_path      end            private      def post_params # allows certain data to be passed via form.          params.require(:post).permit(:user_id, :content)                end        end

pages_controller.rb

class PagesController < ApplicationController        def index    end        def home      @posts = Post.all      @newPost = Post.new    end        def profile      # grab the username from the URL as :id      if (User.find_by_username(params[:id]))       @username = params[:id]      else        # redirect to 404 (root for now)        redirect_to root_path, :notice=> "User not found"      end            @posts = Post.all.where("user_id = ?", User.find_by_username(params[:id]).id)      @newPost = Post.new      @users = User.all          end        def explore      @posts = Post.all    end      end

profile.html.erb

<div class="row">      <div class="col-xs-12">          <div class="jumbotron">              <%= @username %>          </div>      </div>  </div>  <!-- row 2 -->  <div class="row">      <div class="col-xs-3">          <div class="panel panel-default">              <div class="panel-body">                  avatar              </div>          </div>      </div>      <div class="col-xs-6">          <%= render '/components/post_form' %><br>          <% for @p in @posts %>          <div class="panel panel-default post-panel">            <div class="panel-body row">              <div class="col-sm-1">                <img src="/avatar.png" class="post-avatar" height="50px" width="50px"></img>              </div>              <div class="col-sm-11">                <p class="post-title"><span class="post-owner"><a href="/user/<%= User.find(@p.user_id).username %>"><%= User.find(@p.user_id).name %></a></span> <span class="post-creation">- <%= @p.created_at.to_formatted_s(:short) %></span></p>                <p class="post-content"><%= @p.content %></p>              </div>              <div class="col-sm-12">                <p class="post-links">                  <span class="glyphicon glyphicon-comment g-links" aria-hidden="true"></span>                  <span class="glyphicon glyphicon-retweet g-links" aria-hidden="true"></span>                  <span class="glyphicon glyphicon-heart g-links" aria-hidden="true"></span>                  <span class="glyphicon glyphicon-option-horizontal g-links" aria-hidden="true"></span>                  <% if user_signed_in? %>                  <% @posts.each do |post| %>                    <%= link_to 'Delete', post, method: :delete, data: { confirm: 'Are you sure?' } %>                    <% end %>                  <% end %>              </p>              </div>            </div>          </div>          <% end %>      </div>      <div class="col-xs-3">          <div class="panel panel-default">              <div class="panel-body">                  <p>who to follow</p>              </div>          </div>          <div class="panel panel-default">              <div class="panel-body">                  <p>trends</p>            </div>          </div>      </div>  </div>

routes.rb

Rails.application.routes.draw do  devise_for :users  resources :posts  # Define Root URL  root 'pages#index'    # Define Routes for Pages  get '/home' => 'pages#home'  get '/user/:id' => 'pages#profile'  get '/explore' => 'pages#explore'  end  

What should I do in order to fix this problem? Thanks in advance!

Rails Arels: Unsupported argument type: String. Construct an Arel node instead

Posted: 20 Dec 2016 07:57 AM PST

I'm using Arels for creating query. In this query, I use generate_series function. Here is my code:

    def generate_series        Arel::Nodes::NamedFunction.new('GENERATE_SERIES', [start_date, end_day, '1 day'])      end    def start_date        Arel::Nodes::SqlLiteral.new(<<-SQL           CASE WHEN DATE_PART('hour', NOW() AT TIME ZONE 'ICT') < #{Time.now - 3days} THEN (CURRENT_DATE - INTERVAL '14 days') ELSE (CURRENT_DATE - INTERVAL '13 days') END        SQL        )      end        def end_date        Arel::Nodes::SqlLiteral.new(<<-SQL           CASE WHEN DATE_PART('hour', NOW() AT TIME ZONE 'ICT') < #{Time.now} THEN (CURRENT_DATE - INTERVAL '1 day') ELSE CURRENT_DATE END        SQL        )      end  

When I try to test by generate_series.to_sql. I meet exception:

Arel::Visitors::UnsupportedVisitError: Unsupported argument type: String. Construct an Arel node instead.

I try to shorter my code for testing:

def generate_series        Arel::Nodes::NamedFunction.new('GENERATE_SERIES', ['19/11/2012', '20/11/2012', '1 day'])   end  

The problem is same. Please tell me how can I fix this problem.

The association `has_and_belongs_to_many` has an option 'uniq'?

Posted: 20 Dec 2016 07:49 AM PST

I am learning rails with the book 'Rails 4 in Action', and it says the association has_and_belongs_to_many has an option uniq. But it seems it doesn't work as it says. The class below means only unique tags should be retrieved for each ticket, but all the duplicate tags are getting retrieved unlike the book says.

class Ticket < ActiveRecord::Base    ...    has_and_belongs_to_many :tags, uniq: true    ...  

Duplicate tags

I now doubt if the association has_and_belongs_to_many has an option uniq. I guess it doesn't have, and I checked this in the active record association document. http://guides.rubyonrails.org/association_basics.html

Ajax for Follow & Un-follow functions not working - Rails 4

Posted: 20 Dec 2016 07:41 AM PST

this is an Ajax question, which i am completely confused about. Your help would be much appreciated

i already have the below ajax working on the below form

views/users/_show.html.erb  <li class="follow_unfollow_form">    <% if current_user.following?(@user) %>      <span class=""><%= render 'user_unfollow' %></span>    <% else %>      <span class=""><%= render 'user_follow' %></span>    <% end %>  </li>    views/users/_user_unfollow.html.erb  <%= form_for(current_user.active_relationships.find_by(followed_id: @user.id), html: { method: :delete }, remote: true) do |f| %>    <%= f.submit "Unfollow", class: "btn btn_unfollow_submit" %>  <% end %>    views/users/_user_follow.html.erb  <%= form_for(current_user.active_relationships.build, remote: true) do |f| %>    <div><%= hidden_field_tag :followed_id, @user.id %></div>    <%= f.submit "Follow", class: "btn btn_follow_submit" %>  <% end %>    views / relationships / create.js.erb  $(".follow_unfollow_form").html("<%= escape_javascript(render('users/user_unfollow')) %>");    views / relationships / destroy.js.erb  $(".follow_unfollow_form").html("<%= escape_javascript(render('users/user_follow')) %>");  

I am finding it challenging for the ajax to work for the below. could one advise me how to get the ajax for the below to work. The functions works perfectly but the ajax is not working. If i click on the unfollow button for a user i need to mannually referesh the page for the follow button to be displayed . Could you advise or tell me where i am going wrong

views/users/_network.html.erb  <div class="action_btns">    <%= render partial: "form_follow", locals: { user: user } %>  </div>    views/users/_form_follow.html.erb  <span class="btn_follow follow_unfollow_form_network">    <% if current_user.following?(user) %>      <span class="icon_user_refresh">        <!-- render 'user_unfollow' -->        <span class=""><%= render partial: 'user_unfollow_network', locals: { user: user } %></span>      </span>    <% else %>      <span class="icon_user">        <!-- render 'user_follow' -->        <span class=""><%= render partial: 'user_follow_network', locals: { user: user } %></span>      </span>    <% end %>  </span>    views/users/_user_unfollow_network.html.erb  <%= form_for(current_user.active_relationships.find_by(followed_id: user.id), html: { method: :delete }, remote: true) do |f| %>    <%= button_tag type: 'submit', class: "", id: "" do %>      <span data-tooltip aria-haspopup="true" data-options="disable_for_touch:true" class="tip-right" title="Un-Follow">      <i class="fa fa-refresh" aria-hidden="true"></i>      </span>    <% end %>  <% end %>    views/users/_user_follow_network.html.erb  <%= form_for(current_user.active_relationships.build, remote: true) do |f| %>    <div><%= hidden_field_tag :followed_id, user.id %></div>    <%= button_tag type: 'submit', class: "", id: "" do %>      <span data-tooltip aria-haspopup="true" data-options="disable_for_touch:true" class="tip-right" title="Follow">      <i class="fa fa-user" aria-hidden="true"></i>      </span>    <% end %>  <% end %>      I am unsure - will my ajax now look like this?  views / relationships / create.js.erb  $(".follow_unfollow_form").html("<%= escape_javascript(render('users/user_unfollow')) %>");  $(".follow_unfollow_form_network").html("<%= escape_javascript(render('users/user_unfollow_network')) %>");    views / relationships / destroy.js.erb  $(".follow_unfollow_form").html("<%= escape_javascript(render('users/user_follow')) %>");  $(".follow_unfollow_form_network").html("<%= escape_javascript(render('users/user_follow_network')) %>");  

Generate unique sequential id

Posted: 20 Dec 2016 08:16 AM PST

How do I generate a unique sequential ID (that follows a pattern), each time a record is created? How do I address concurrency issues?

I want this ID to follow a fixed pattern. e.g.: ABC00001, ABC00002, ABC00003, etc

Radio button label is in wrong place

Posted: 20 Dec 2016 08:02 AM PST

Instead of showing label next to radio button, it is shown above it. screen capture

new.html.erb:    <div class="center jumbotron">    <h2><%= t(:creating_task) %></h2>    <%= form_for(@task, url: new_task_path) do |f| %>      ...          <div>        <%= label :form_type, t(:multiple_choice) %>             <%= f.radio_button :form_type, '1' %>        <div class="reveal-if-active">          </div>      </div>      <div>        <%= label :form_type, t(:fill_gap) %>        <%= f.radio_button :form_type, '2' %>        <div class="reveal-if-active">        </div>      </div>      <% end %>  </div>  

I am using bootstrap and even when I copy bootstrap example, which looks like this: enter image description here It looks like in picture above.

What could be the reason?

@EDIT

    <h2>Tworzenie zadania</h2>      <form class="new_task" id="new_task" enctype="multipart/form-data" action="/pl/tasks/new" accept-charset="UTF-8" method="post"><input name="utf8" value="✓" type="hidden"><input name="authenticity_token" value="xxx" type="hidden">          <label for="text_Kategoria">Kategoria</label>        <select name="task[category]" id="task_category"><option value=""></option>  <option value="1">Test</option></select>          <label for="text_Obraz">Obraz</label>        <input name="task[asset_name]" id="task_asset_name" type="file">        <!-- dodać podgląd -->          <label for="text_Opis">Opis</label>        <textarea class="form-control" name="task[text]" id="task_text"></textarea>          <!-- dodać poprawne wyświetlanie równań -->        <label for="form_type_Rodzaj zadania">Rodzaj zadania</label>            <div>          <label for="form_type_Wielokrotny wybór">Wielokrotny wybór</label>               <input value="1" name="task[form_type]" id="task_form_type_1" type="radio">          <div class="reveal-if-active">            </div>        </div>        <div>          <label for="form_type_Wypełnianie luk">Wypełnianie luk</label>          <input value="2" name="task[form_type]" id="task_form_type_2" type="radio">          <div class="reveal-if-active">            </div>        </div>    </form>  

CSS:

@import "bootstrap-sprockets";  @import "bootstrap";      /* universal */    body {    padding-top: 60px;  }    section {    overflow: auto;  }    textarea {    resize: vertical;  }    .center {    text-align: center;  }    .center h1 {    margin-bottom: 10px;  }    /* header */    #test-name {    margin-right: 10px;    font-size: 1.7em;    color: #fff;    letter-spacing: -1px;    padding-top: 50px;    font-weight: bold;    float: left;  }    #user-link {    margin-right: 10px;    font-size: 1.7em;    color: #fff;    letter-spacing: -1px;    padding-top: 9px;    font-weight: bold;    float: right;    text-decoration: none;   }    /* footer */    footer {    margin-top: 45px;    padding-top: 5px;    border-top: 1px solid #eaeaea;    color: #777;  }    footer a {    color: #555;  }    footer a:hover {    color: #222;  }    footer small {    float: left;  }    footer ul {    float: right;    list-style: none;  }    footer ul li {    float: left;    margin-left: 15px;  }    /* forms */    input, textarea, select, .uneditable-input {    border: 1px solid #bbb;    width: 100%;    margin-bottom: 15px;    -moz-box-sizing: border-box;    -webkit-box-sizing: border-box;    box-sizing: border-box;  }    input {    height: auto !important;  }    #error_explanation {    color: red;    ul {      color: red;      margin: 0 0 30px 0;    }  }    .field_with_errors {    @extend .has-error;    .form-control {      color: $state-danger-text;    }  }    .reveal-if-active {    opacity: 0;    max-height: 0;    overflow: hidden;    transform: scale(0.8);    transition: 0.5s;    input[type="radio"]:checked ~ &,    input[type="checkbox"]:checked ~ & {      opacity: 1;      max-height: 100px;      overflow: visible;      padding: 10px 20px;      transform: scale(1);    }  }  /* Users index */    .users {    list-style: none;    margin: 0;    li {      overflow: auto;      padding: 10px 0;      border-bottom: 1px solid $gray-lighter;    }  }  

rake aborted error when deploying to heroku

Posted: 20 Dec 2016 07:10 AM PST

Am deploying a new rails 5 app in heroku and it's showing me this css error, but from my side everything looks good, i tried some methods but all for vain.

remote:        rake aborted!  remote:        Sass::SyntaxError: Invalid CSS after "...: 24px; color: ": expected expression (e.g. 1px, bold), was "@color-primary; }"  remote:        (sass):6889  

I tried running rake assets:precompile but it also goes fine

my gemfile

source 'https://rubygems.org'      # 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  # Use Puma as the app server  gem 'puma', '~> 3.0'  # Use SCSS for stylesheets  gem 'sass-rails', '~> 5.0'  # Use Uglifier as compressor for JavaScript assets  gem 'uglifier', '>= 1.3.0'  # Use CoffeeScript for .coffee assets and views  gem 'coffee-rails', '~> 4.2'  gem 'omniauth-facebook', '~> 4.0'    group :production do    gem 'pg'  end    # 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'  # 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 :development, :test do    # Call 'byebug' anywhere in the code to stop execution and get a debugger console    gem 'byebug', platform: :mri    gem 'sqlite3'  end    group :development do    # Access an IRB console on exception pages or by using <%= console %> anywhere in the code.    gem 'web-console'  end    # Windows does not include zoneinfo files, so bundle the tzinfo-data gem  gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]  

has_many of itself though

Posted: 20 Dec 2016 06:57 AM PST

I'm working on a maze project in rails, and ironically, I got lost. So far, I'm pretty new with has_many_though relationships between models, so what if a model has many of itself through something ?

Basically, Each Room has many Rooms. I created a Tunnel model to connect these rooms, so that a room is connected to many others through tunnels. But it gets trickier when it comes to building these relations.

class Room < ApplicationRecord      has_many :tunnels    has_many :rooms, through: :tunnels    end  

And my Tunnel gets to connect two rooms

class Tunnel < ApplicationRecord    belongs_to :lemmin_room, :foreign_key => "room1_id"    belongs_to :lemmin_room, :foreign_key => "room2_id"  end  

Rails documentation is pretty clear when it comes toe ModelA has many Model B through ModelC, but I don't think it ever mentions ModelA = ModelB.

Pattern to render multiple coffee

Posted: 20 Dec 2016 07:07 AM PST

I have a task model which is related to the user and project models.

When I create/update a task, I need to do an update in the view async, not only for the task change/addition, but to the project and user info (because some of that data might change too).

I have this in the controller:

def create    @task = Task.new(params[:task])    @project = Project.find(params[:project_id])      respond_to do |format|      if @task.save        format.html { redirect_to @task, notice: 'Task was successfully created.' }        format.json { render json: @task, status: :created, location: @task }      else        format.html { render action: "new" }        format.json { render json: @task.errors, status: :unprocessable_entity }      end    end  end  

And my tasks/create.js.coffee

# Update task table  $('#mytable').append("<%= j render(partial: 'tasks/task', locals: { t: @task }) %>")    # Update user data  $('.user-data').html("<%= j render(partial: 'users/user_widget', locals: { u: current_user }) %>")    # Update project data  $('.project-data').html("<%= j render(partial: 'projects/project_widget', locals: { p: @project }) %>")  

And it works great. I see 2 issues:

  • In every render of .js.coffee I add, I am repeating the code too much. I duplicate exactly the same code for updating project and user data, on tasks update, tasks destroy, and I would do the same for a new model which might affect the user and the project

  • It seems weird to handle project and user data in tasks/create.js.coffee

Therefore, I am looking for a better pattern to handle this stuff, any ideas?

EDIT (to clarify): I think achieving something like this would be better:

tasks/create.js.coffee

# Update task table  $('#mytable').append("<%= j render(partial: 'tasks/task', locals: { t: @task }) %>")    UserData.refresh()  ProjectData.refresh()  

However, I can't do that because I need to render the partial each time, so I would have to do something weird like passing the html partial to those refresh() functions, and it would be pretty the same as the previous way. This is just a way that came to my mind, but I would like to hear your ideas if any.

How can I run a cron command with environmental variables set by kubernetes secret

Posted: 20 Dec 2016 06:56 AM PST

I'm using kubernetes secret as my environment variable (http://kubernetes.io/docs/user-guide/secrets/#using-secrets-as-environment-variables) and it works fine for my rails application and bash command.

echo $RAILS_ENV #=> staging  

But it doesn't work when executing cron process.

I've read some post to understand cron process (e.g. http://unix.stackexchange.com/questions/27289/how-can-i-run-a-cron-command-with-existing-environmental-variables) and know that I should source .profile or .bashrc before executing cron command like.

* * * * * . $HOME/.profile; /bin/bash -l -c 'echo rails_env=$RAILS_ENV >> /tmp/cron_test.log'    * * * * * . $HOME/.bashrc; /bin/bash -l -c 'echo rails_env=$RAILS_ENV >> /tmp/cron_test.log'  

but both doesn't work for me ˊˋ

result

rails_env=  

Any help will be appreciated!

How to handle 'Unclosed quotation mark after the character string' in Ruby?

Posted: 20 Dec 2016 08:12 AM PST

I'm getting an error when trying to grab html from a webpage and saving it to my active record object. The message I'm getting is, Unclosed quotation mark after the character string. Is there a function in Ruby or a way to go about checking and then correcting instances where this happens prior to saving the record to the database? The full error from TinyTDS is below...

ActiveRecord::StatementInvalid: TinyTds::Error: Unclosed quotation mark after the character string '  

Update

My apologies, didn't realize I hadn't added enough information. I'll happily add any requests. Let me start with the log, and also to the part about "escaping my data" correctly -- It's HTML from an outside source that's throwing the error. So to that point I guess perhaps I go back to my initial question which was how do I go about locating where the unclosed quotation mark is, and then correcting it?

Error Log

  SQL (27.8ms)  BEGIN TRANSACTION    SQL (2.8ms)  EXEC sp_executesql N'UPDATE [school_player_scrapes] SET [biography_text] = @0, [headshot_url] = @1, [updated_at] = @2 WHERE [school_player_scrapes].[id] = @3; SELECT @@ROWCOUNT AS AffectedRows', N'@0 nvarchar(max), @1 nvarchar(4000), @2 datetime, @3 int', @0 = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">  <html><body><td class="sm PlayerBioArticleContent" colspan="2">                  <p><strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Butte College:�</span></strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Attended Butte CC in 2015.</span></p>  <p><strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">High School:�</span></strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Attended North Little Rock High Scchool . . . Ranked a two-star recruit by Scout.com and 247 Sports . . . Recruited by schools such as Auburn, Georgia Tech and Minnesota among others.�</span></p>              </td></body></html>  ', @1 = N'http://image.cdnllnwnl.xosnetwork.com/pics33/200/IQ/IQQZSKTMHZNYBCD.20160807033143.jpg', @2 = '12-15-2016 08:24:50.657', @3 = 7444  [["biography_text", "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html><body><td class=\"sm PlayerBioArticleContent\" colspan=\"2\">\n\t\t\t\t<p><strong><span style=\"font-family: arial, helvetica, sans-serif; font-size: small;\">Butte College:\xA0</span></strong><span style=\"font-family: arial, helvetica, sans-serif; font-size: small;\">Attended Butte CC in 2015.</span></p>\r\n<p><strong><span style=\"font-family: arial, helvetica, sans-serif; font-size: small;\">High School:\xA0</span></strong><span style=\"font-family: arial, helvetica, sans-serif; font-size: small;\">Attended North Little Rock High Scchool . . . Ranked a two-star recruit by Scout.com and 247 Sports . . . Recruited by schools such as Auburn, Georgia Tech and Minnesota among others.\xA0</span></p>\n\t\t\t</td></body></html>\n"], ["headshot_url", "http://image.cdnllnwnl.xosnetwork.com/pics33/200/IQ/IQQZSKTMHZNYBCD.20160807033143.jpg"], ["updated_at", Thu, 15 Dec 2016 08:24:50 EST -05:00], ["id", 7444]]  TinyTds::Error: Unclosed quotation mark after the character string '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">  <html><body><td class="sm PlayerBioArticleContent" colspan="2">                  <p><strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Butte College:'.: EXEC sp_executesql N'UPDATE [school_player_scrapes] SET [biography_text] = @0, [headshot_url] = @1, [updated_at] = @2 WHERE [school_player_scrapes].[id] = @3; SELECT @@ROWCOUNT AS AffectedRows', N'@0 nvarchar(max), @1 nvarchar(4000), @2 datetime, @3 int', @0 = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">  <html><body><td class="sm PlayerBioArticleContent" colspan="2">                  <p><strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Butte College:�</span></strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Attended Butte CC in 2015.</span></p>  <p><strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">High School:�</span></strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Attended North Little Rock High Scchool . . . Ranked a two-star recruit by Scout.com and 247 Sports . . . Recruited by schools such as Auburn, Georgia Tech and Minnesota among others.�</span></p>              </td></body></html>  ', @1 = N'http://image.cdnllnwnl.xosnetwork.com/pics33/200/IQ/IQQZSKTMHZNYBCD.20160807033143.jpg', @2 = '12-15-2016 08:24:50.657', @3 = 7444    SQL (0.8ms)  IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION  Performed ScrapeSchoolRosterJob from Sidekiq(high_priority) in 2787.93ms  ActiveRecord::StatementInvalid: TinyTds::Error: Unclosed quotation mark after the character string '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">  <html><body><td class="sm PlayerBioArticleContent" colspan="2">                  <p><strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Butte College:'.: EXEC sp_executesql N'UPDATE [school_player_scrapes] SET [biography_text] = @0, [headshot_url] = @1, [updated_at] = @2 WHERE [school_player_scrapes].[id] = @3; SELECT @@ROWCOUNT AS AffectedRows', N'@0 nvarchar(max), @1 nvarchar(4000), @2 datetime, @3 int', @0 = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">  <html><body><td class="sm PlayerBioArticleContent" colspan="2">                  <p><strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Butte College:�</span></strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Attended Butte CC in 2015.</span></p>  <p><strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">High School:�</span></strong><span style="font-family: arial, helvetica, sans-serif; font-size: small;">Attended North Little Rock High Scchool . . . Ranked a two-star recruit by Scout.com and 247 Sports . . . Recruited by schools such as Auburn, Georgia Tech and Minnesota among others.�</span></p>              </td></body></html>  ', @1 = N'http://image.cdnllnwnl.xosnetwork.com/pics33/200/IQ/IQQZSKTMHZNYBCD.20160807033143.jpg', @2 = '12-15-2016 08:24:50.657', @3 = 7444      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:336:in `each'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:336:in `handle_to_names_and_values_dblib'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:325:in `handle_to_names_and_values'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:300:in `_raw_select'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:295:in `block in raw_select'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:466:in `block in log'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.0/lib/active_support/notifications/instrumenter.rb:20:in `instrument'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract_adapter.rb:460:in `log'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:295:in `raw_select'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:244:in `sp_executesql'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:19:in `exec_query'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract/database_statements.rb:95:in `exec_update'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-sqlserver-adapter-4.2.3/lib/active_record/connection_adapters/sqlserver/database_statements.rb:39:in `exec_update'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract/database_statements.rb:114:in `update'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/connection_adapters/abstract/query_cache.rb:14:in `update'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activerecord-4.2.0/lib/active_record/relation.rb:88:in `_update_record'  ... 57 levels...      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:337:in `call'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:337:in `block in simple'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:92:in `call'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:92:in `_run_callbacks'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:734:in `_run_perform_callbacks'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:81:in `run_callbacks'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activejob-4.2.0/lib/active_job/execution.rb:31:in `perform_now'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/activejob-4.2.0/lib/active_job/execution.rb:16:in `perform_now'      from (irb):2      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/railties-4.2.0/lib/rails/commands/console.rb:110:in `start'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/railties-4.2.0/lib/rails/commands/console.rb:9:in `start'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:68:in `console'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/railties-4.2.0/lib/rails/commands/commands_tasks.rb:39:in `run_command!'      from /home/deploy/bane/shared/bundle/ruby/2.2.0/gems/railties-4.2.0/lib/rails/commands.rb:17:in `<top (required)>'      from bin/rails:4:in `require'  

Ruby replace only part of the Matching String

Posted: 20 Dec 2016 07:16 AM PST

How do I replace only part of the String in a Ruby code?

Supposed I have a text file that contains multiple occurrences of the keyword "JVM_MEM_ARGS_64BIT"

JVM_MEM_ARGS_64BIT="-Xms512m -Xmx512m"  

and I only want to replace the first occurrence, I can use the #sub instead of gsub

a.sub('JVM_MEM_ARGS_64BIT="-Xms512m -Xmx512m"', 'JVM_MEM_ARGS_64BIT="-Xms512m -Xmx1024m"')  

however not all files contains

JVM_MEM_ARGS_64BIT="-Xms512m -Xmx512m"  

some could be

JVM_MEM_ARGS_64BIT="-Xms256m -Xmx512m"  

I am not sure how to do this in a ruby code? I can search for the keyword "JVM_MEM_ARGS_64BIT" only but how do I delete the existing value assignment and replace it with JVM_MEM_ARGS_64BIT="-Xms512m -Xmx1024m

Newbie Ruby developer.

Empty String When Performing Search in Rails 4

Posted: 20 Dec 2016 06:31 AM PST

I am trying to perform a search, but when I search all I keep getting back is an empty string and I can't figure out why. Below is all of the relevant code. Thanks in advance.

html.erb

<a tabindex="0" class="button btn-transparent" id="listing-agent-selector" role="button" data-toggle="popover">Agents <span class="caret"></span></a>    <div class="input-group input-group-sm">    <% @agents.each do |agent| %>      <div class="lord-jesus">        <%= check_box_tag 'agent_id_list[]', agent.id, @listing_search.agent_ids.include?(agent.id.to_s) %> <%= agent.name %>      </div>    <% end %>  </div>    <%= f.hidden_field :agent_id_list, id: "listing_agent_values" %>  

jQuery:

$('#listing-agent-selector').popover({    html: true,    trigger: 'manual',    placement: 'bottom',    template: '<div class="popover listing-agent-pop" role="tooltip"><div class="arrow"></div><div class="popover-content"></div></div>',    content: function() {      return $('#listing-agent-popover').html();    }  });    $('#new_listing_search_form').on('change', 'input[name="agent_id[]"]', function(e) {    var agentIds = $('input[name="agent_id[]"]:checked', '#new_listing_search_form .popover')      .map(function() {        return this.value;      })      .toArray();      $('#listing-agent-values').val(agentIds.join());      $('input[name="agent_id[]"]', '#listing-agent-popover').attr('checked', false);      agentIds.forEach(function(agentId) {      var checkboxName = 'input[name="agent_id[]"][value="' + agentId + '"]';      $(checkboxName, '#listing-agent-popover').attr('checked', true);    });  });  

ListingSearchForm:

attribute :agent_id_list, String    def agent_ids    String(agent_id_list).split(',')      .reject(&:blank?)  end    def agent_id_list_scope    if agent_ids.empty?      Listing.all    else      Listing.where("listing_agent_id IN (?) OR sales_agent_id IN (?)", agent_ids, agent_ids)    end  end  

ListingSearches Controller:

class ListingSearchesController < ApplicationController    def index    @listing_search = ListingSearchForm.new(listing_search_params)    search_token = @listing_search.serialize      RecordListingSearchEntryJob.perform_later(search_token, current_agent)      redirect_to index_path(q: search_token)  end    private    def listing_search_params      params.require(:listing_search_form)            .permit(:address,                    :agent_id_list,                    :amenity_list,                    :date_available,                    :min_baths,                    :bed_list,                    :exclusive,                    :featured,                    :listing_id,                    :max_price,                    :min_price,                    :min_price_per_bed,                    :max_price_per_bed,                    :neighborhood_id_list,                    :owner_pays,                    :pets,                    :min_square_feet,                    :max_square_feet,                    :subway_id_list      )  end  end  end  

ListingsController:

@listings = if params[:q]              @listing_search = ListingSearchForm.deserialize(params[:q])              @listing_search.search            else              Listing.all            end  

Can't connect to PostgreSQL with Rails and Capistrano

Posted: 20 Dec 2016 06:17 AM PST

I'm trying to deploy my Rails 5 application using Postgres to a VPS via Capistrano. It keeps failing, though - giving me a PG::ConnectionBad: FATAL: password authentication failed for user 'sys_user'.

The relevant settings of my database.yml are:

production:    <<: *default    database: <%= ENV['RDS_DB_NAME'] %>    username: <%= ENV['RDS_USERNAME'] %>    password: <%= ENV['RDS_PASSWORD'] %>    host: <%= ENV['RDS_HOSTNAME'] %>    port: <%= ENV['RDS_PORT'] %>  

All these environment variables have been set in /etc/environment - this is definitely the case because it's picking up the RDS_USERNAME as sys_user. The password of the database is the same as the variable RDS_PASSWORD. The port, hostname etc. are all the same also.

I'm stumped. Please help.

How to save record in DB as text not as id

Posted: 20 Dec 2016 07:23 AM PST

I'm doing meal ordering system, I'm new in Rails and I'm wondering how can I save record (ordered meal from restaurant) in the DB as text. For example I have a list of restaurants and meals in my db/seed.rb and when I order a meal from the restaurant in my order view intead of see ordered meal (name of the meal and name of the restaurant) I see id of restaurant and id of meal. I know it's probobly easy to fix, but I have no idea go to do this.

db/seed.rb     Restaurant.create(name: "PizzaHut")   Restaurant.create(name: "Salad Story")   Restaurant.create(name: "KFC")     Meal.create(name: "PizzaHut Special - 32cm", restaurant_id: Restaurant.find_by(name: "PizzaHut").id)   Meal.create(name: "PizzaHut Special - 42cm", restaurant_id: Restaurant.find_by(name: "PizzaHut").id)   Meal.create(name: "Pepperoni - 32cm", restaurant_id: Restaurant.find_by(name: "PizzaHut").id)   Meal.create(name: "Pepperoni - 42cm", restaurant_id: Restaurant.find_by(name: "PizzaHut").id)   Meal.create(name: "Hawaii - 32cm", restaurant_id: Restaurant.find_by(name: "PizzaHut").id)   Meal.create(name: "Hawaii - 42cm", restaurant_id: Restaurant.find_by(name: "PizzaHut").id)   Meal.create(name: "Diablo - 32cm", restaurant_id: Restaurant.find_by(name: "PizzaHut").id)   Meal.create(name: "Diablo - 42cm", restaurant_id: Restaurant.find_by(name: "PizzaHut").id)   Meal.create(name: "Longer + Small Drink (Coca-Cola, Fanta, Sprite)", restaurant_id: Restaurant.find_by(name: "KFC").id)   Meal.create(name: "Longer + Large Drink (Coca-Cola, Fanta, Sprite)", restaurant_id: Restaurant.find_by(name: "KFC").id)   Meal.create(name: "Greek Salad - Medium", restaurant_id: Restaurant.find_by(name: "Salad Story").id)   Meal.create(name: "Greek Salad - Large", restaurant_id: Restaurant.find_by(name: "Salad Story").id)   Meal.create(name: "Salad Story Special - Medium", restaurant_id: Restaurant.find_by(name: "Salad Story").id)   Meal.create(name: "Salad Story Special - Large", restaurant_id: Restaurant.find_by(name: "Salad Story").id)  

staticpages/home.html.erb

 <h1 class="jumbotron-font">Order your meal</h1>       <div class="row">         <div class="col-md-6 col-md-offset-3">           <%= form_for(:orders, url: new_order_path) do |f| %>               <%= f.label :restaurant, "Restaurant" %>             <%= f.collection_select :restaurant_id, Restaurant.order(:name), :id,            :name, {prompt: "Select a restaurant"}, {class: "form-control"} %>               <%= f.label :meal, "Choose your meal" %>             <%= f.grouped_collection_select :meal_id, Restaurant.order(:name),              :meals, :name, :id, :name, {prompt: "Select a meal"},                                                    {class: "form-control"} %>               <%= f.label :suggestions, "Suggestions" %>             <%= f.text_area :suggestions, rows: "4", placeholder: "e.g. I'd like to change sweetcorn for olives..." %>               <%= f.submit "Place your order", class: "btn btn-primary" %>           <% end %>         </div>       </div>  

And db/schema.rb

 ActiveRecord::Schema.define(version: 20161220125950) do       create_table "meals", force: :cascade do |t|       t.string   "name"       t.integer  "restaurant_id"       t.datetime "created_at",    null: false       t.datetime "updated_at",    null: false       t.index ["restaurant_id"], name: "index_meals_on_restaurant_id"     end       create_table "orders", force: :cascade do |t|       t.string   "restaurant"       t.string   "meal"       t.text     "suggestions"       t.integer  "user_id"       t.datetime "created_at",      null: false       t.datetime "updated_at",      null: false       t.string   "restaurant_id"       t.string   "meal_id"       t.index ["user_id", "created_at"], name: "index_orders_on_user_id_and_created_at"       t.index ["user_id"], name: "index_orders_on_user_id"     end       create_table "restaurants", force: :cascade do |t|       t.string   "name"       t.datetime "created_at",      null: false       t.datetime "updated_at",      null: false     end       create_table "users", force: :cascade do |t|       t.string   "provider"       t.string   "uid"       t.string   "name"       t.datetime "created_at", null: false       t.datetime "updated_at", null: false     end     end  

My logs:

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"TVdB/YJ8W2fQD0XslA7KwlY2WHPPTSsI6Tx18CE1v6vF9zJLjM5nFd6lO/gSrPwsy/fCnra54TeAtxrwGyIGoQ==", "orders"=>{"restaurant_id"=>"1", "meal_id"=>"11", "suggestions"=>""}, "commit"=>"Place your order"}     User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]      (0.1ms)  begin transaction     CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]     Restaurant Load (0.1ms)  SELECT  "restaurants".* FROM "restaurants" WHERE "restaurants"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]     SQL (91.1ms)  INSERT INTO "orders" ("suggestions", "user_id", "created_at", "updated_at", "restaurant_id", "meal_id") VALUES (?, ?, ?, ?, ?, ?)  [["suggestions", ""], ["user_id", 1], ["created_at", 2016-12-20 14:05:13 UTC], ["updated_at", 2016-12-20 14:05:13 UTC], ["restaurant_id", "1"], ["meal_id", "11"]]      (241.2ms)  commit transaction  

* UPDATE *

 class Order < ApplicationRecord     belongs_to :user     belongs_to :restaurant   end     class User < ApplicationRecord     has_many :orders     has_many :restaurants, through: :orders   end     class Meal < ApplicationRecord     belongs_to :restaurant   end     class Restaurant < ApplicationRecord     has_many :orders     has_many :meals     has_many :users, through: :orders   end  

From view I have just order/index.html.erb

 <% @orders.each do |order| %>     <div class="row">       <div class="col-md-6 col-md-offset-3">         <%= order.restaurant_name %>         <%= order.meal_name %>         <%= order.suggestions %>       </div>     </div>   <% end %>  

It's simple application, just for practice, so I want to do single page application without actually confirming the order by restaurant. I want to be able to make the order and then see in history list of all orders.

vagrant error, not start global-status

Posted: 20 Dec 2016 06:07 AM PST

I've got this error when I tried to do the command vagrant global-status on my server:

    Vagrant experienced a version conflict with some installed plugins!  This usually happens if you recently upgraded Vagrant. As part of the  upgrade process, some existing plugins are no longer compatible with  this version of Vagrant. The recommended way to fix this is to remove  your existing plugins and reinstall them one-by-one. To remove all  plugins:        rm -r ~/.vagrant.d/plugins.json ~/.vagrant.d/gems    Note if you have an alternate VAGRANT_HOME environmental variable  set, the folders above will be in that directory rather than your  user's home directory.    The error message is shown below:    Bundler could not find compatible versions for gem "bundler":    In Gemfile:      vagrant (= 1.8.5) was resolved to 1.8.5, which depends on        bundler (~> 1.12.5)      Current Bundler version:      bundler (1.13.6)  This Gemfile requires a different version of Bundler.  Perhaps you need to update Bundler by running `gem install bundler`?    Could not find gem 'bundler (~> 1.12.5)', which is required by gem 'vagrant (= 1.8.5)', in any of the sources.  

it start after updates on my debian machine

thanks to all

I am not able to load layout while rendering in rails

Posted: 20 Dec 2016 06:08 AM PST

can anybody help me out , why i am not able to load particular layout for particular action with

render :layout => "application"   

application.html.erb present in layouts folder. is i have to do some settings for layout?

my code is :-

class PageController < ApplicationController     layout false    def index1      render :layout => "application"    end  end  

error when launching rails server

Posted: 20 Dec 2016 06:06 AM PST

I have this error when i try to execute "rails server" on debian8: Please help

/usr/local/bin/rails:23:in load': cannot load such file -- /usr/share/rubygems-integration/all/gems/railties-4.1.8/bin/rails (LoadError) from /usr/local/bin/rails:23:in'

Changes between two hashes in ruby

Posted: 20 Dec 2016 06:14 AM PST

I have two hashes with the below format

mydetails[x['Id']] = x['Amount']  

this would contain data like

hash1 = {"A"=>"0", "B"=>"1","C"=>"0", "F"=>"1"}  hash2 = {"A"=>"0", "B"=>"3","C"=>"0", "E"=>"1"}  

I am expecting an output something like:

Differences in hash: "B, F, E"

Any help is very much appreciated.

Using Ruby sub method with array of strings

Posted: 20 Dec 2016 06:27 AM PST

I'm using Ruby's sub method to clean some strings this way:

test_string = 'we serve food and drinks'  => "we serve foo and drinks"  test_string.sub('and drinks', '')  => "we serve foo"   

How can I use the same method over an array of strings like this one:

test_array = ['we serve foo and drinks', 'we serve toasts and drinks', 'we serve alcohol and drinks']  

I tried something like this but doesn't work:

test_array.each do |testArray|    test_array.sub('and drinks', '')  end  => ["we serve foo and drinks", "we serve toasts and drinks", "we serve kale and drinks"]  

How can I convert xml into json in Ruby on rails

Posted: 20 Dec 2016 05:52 AM PST

<result>      <sequence id="148"></sequence>      <sequence id="211"></sequence>      <sequence id="81">!Kyle OP Test</sequence>      <sequence id="197">(SS) AnikSIB - 1 Hour Reminder</sequence>      <sequence id="198">(SS) AnikSIB - 5 minutes Reminder</sequence>  <result>  

How can I convert the above xml into json I want sequence id like 148 ,211,81,197 and !Kyle OP Test ,(SS) AnikSIB - 1 Hour Reminder What I am trying : Hash.from_xml(xmlresponce) And my Output is:

{    "result": {      "sequence": [        {          "id": "148"        },        {          "id": "211"        },        "!Kyle OP Test",        "(SS) AnikSIB - 1 Hour Reminder",        "(SS) AnikSIB - 5 minutes Reminder",  

I want the sequence id of !Kyle OP Test which I am not getting.

Auto fill doesn't work on edit with image uploader

Posted: 20 Dec 2016 05:46 AM PST

I trying to create a blog with a obligatory image, but after create, when i try to edit this blog, his image appears on thmbnail but not in field and i have to select the image again.

For upload image i use the carrierwave gem.

My model

class Blog < ActiveRecord::Base  validates :name, :description, :picture, presence: true    mount_uploader :picture, BlogPictureUploader    def picture_url    picture.url  end  

My view

= simple_form_for [blog] do |f|   .row    .col-md-6      .panel.panel-default        .panel-heading Foto        .panel-body          .thumbnail class="#{blog.picture? ? "" : "hide"}"            = image_tag blog.picture          p= f.input :picture, label: 'Selecione a foto:', hint: 'A foto deve ter 270x270.'  

My controller

 class BlogsController < ApplicationController   expose(:blog, attributes: :blog_params)     def update     authorize blog     blog.save     respond_with blog, location: [:blog]   end  

The behavior on edit: edit view after click button

Rails how to redirect to the same page without query params?

Posted: 20 Dec 2016 05:33 AM PST

I have route:

resource :setup  

And I have url (GET): http://some.com/setup?email=yoo@some.com when the user clicks link I want to redirect him to http://some.com/setup i.e without ...?email=yoo@some.com I wanted to know is that possible?

I tried to do smth like this:

setup_controller.rb

def show    redirect_to setup_boom_path  end    def boom    redirect_to setup_path  end  

but still getting: .... redirected you too many times.

how can define another ajax into ajax success body or how to define inner ajax in rails

Posted: 20 Dec 2016 05:16 AM PST

I want to define another ajax into ajax success body and how to define inner ajax.

First ajax is success full execute then send ajax should be call and perform the task.

below code into this file _step.html.erb

this is my bootstrap modal button when i will click then my popup menu call

<button type="button" class="btn btn-default text-primary active" data-toggle="modal" data-candi_next_step="<%= s %>" data-target="#myModal_<%= applied_candidate.id %>_<%= @s1 = s %>">              <%= l.workflow_step %></button>  

this is my bootstrap modal

  <div class="modal fade" id="myModal_<%= applied_candidate.id %>_<%= @s1 %>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">    <div class="modal-dialog" role="document">      <div class="modal-content">        <div class="modal-header">          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>        </div>              <div class="modal-body">          <h2 class="text-center">Schedule<span> L1 interview</span></h2>          <div class="post-new-job head-border" style="margin-bottom: -10%;"></div>              <%= form_for :validation_screens, url: candidate_capture_validation_process_path(@validation_screen), method: :get do |f| %>                   <div class="form-group">                <label class="control-label">Role / Designation</label>                <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>                  <%= f.text_field :role, {disabled: true, :value=>job.title, class: 'form-control' } %>                </div>              </div>                <div class="form-group">                <label class="control-label">Candidate Name</label>                <div class="input-group"> <span class="input-group-addon"> <i class="fa fa-user"></i> </span>                  <%= f.text_field :applied_candidate_name, {disabled: true, :value=>applied_candidate.first_name+" "+applied_candidate.last_name, class: 'form-control' } %>                </div>              </div>  <div class="col-md-2"></div>               <div class="form-group">                <%= f.submit "Send Email", :class => "candidate_next_step_#{applied_candidate.id}_#{@s1}" %>               </div>                   <%- end -%>               </div>      </div>    </div>  </div>  

then I click on Send Email Button then my ajax will be call

 $('#myModal_<%= applied_candidate.id%>_<%= @s1 %>').on('show.bs.modal', function (event) {      var button = $(event.relatedTarget);      var candidate_next_step_value = button.data('candi_next_step');      var modal = $(this)      modal.find('.mydata input').val(candidate_next_step_value);    });        $('.candidate_next_step_<%=applied_candidate.id%>_<%= @s1 %>').click(function(){          $.ajax({        async: 'true',        type: 'GET',        url: '/candidate/jobs/update_work_flow',        data: {          user_id: '<%=applied_candidate.id%>',          name:  '<%=applied_candidate.first_name%>'+'<%=applied_candidate.last_name%>',          job_id: '<%= job.id%>',          s: '<%= @s1 %>',          job_title: '<%= job.title %>',          apply: '<%=user.first_name%>'+ '<%=user.last_name%>',          client: '<%=@client.company_name%>',          current: "<%= offer_state.current_step %>"         },        success: function(resp){          $('#a_<%=applied_candidate.id%>').html(resp);          **Here i want to call same above ajax**          console.log(resp);        },error: function(resp){             alert(resp);        }     });     return false;    });  

I want to call same above ajax code in place Here i want to call same above ajax of this line

I try and my data is insert into table but my browser is stuck like this enter image description here

I don't have so much knowledge about ajax, please can any one tell me where i am wrong and what is problems

How to validate a field with jQuery Validation in rails

Posted: 20 Dec 2016 06:25 AM PST

I followed this tutorial to validate a form in rails with the jquery validation plugin: https://sleekd.com/tutorials/jquery-validation-in-ruby-on-rails/

The validations work me correctly except when I have to validate a single field, in the tutorial explain how to validate an email, but I have already tried everything, someone who can help me please thank you

This is an example:

$(document).ready(function () {    $("#new_user").validate({      debug: true,      rules: {        "user[email]": {required: true, email: true, remote:"/users/check_email" },        "user[password]": {required: true, minlength: 6},        "user[password_confirmation]": {required: true, equalTo: "#user_password"}      }    });  });      

in controller

def check_email    @user = User.find_by_email(params[:user][:email])      respond_to do |format|      format.json { render :json => !@user }    end  end  

in routes.rb:

 map.check_email "users/check_email", :controller => "users", :action => "check_email"   map.resources :users  

custom sign in form for devise not working

Posted: 20 Dec 2016 05:05 AM PST

I am currently trying to create a custom sign in form for users created by devise. When the sign-in form is submitted i get an error saying invalid email or password even though the details are correct. I am using ajax to render the forms from partials so could be the thing causing some trouble but i am not sure.

here is the form

<span id="close-button" class="glyphicon glyphicon-remove pull-right"></span>  <%= form_tag(new_user_session_path, method: :post) do %>      <div class="form-group">          <%= label_tag :email %>          <%= email_field_tag :email, nil, :class => "form-control"    %>      </div>      <div class="form-group">          <%= label_tag :password %>          <%= password_field_tag :password, nil, :class => "form-control" %>      </div>      <%= submit_tag "Sign In", class: "btn btn-primary" %>  <% end %>    <script>      $('#close-button').on('click', function() {          $(this).parent().html(" ");      });  </script>  

here is my routes file

Rails.application.routes.draw do    devise_for :users, controllers: { registrations: 'users/registrations',                                      sessions: 'users/sessions' }     # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html     root 'pages#index'      devise_scope :user do      get '/sign_up_form' => 'users/registrations#sign_up_form', as: 'user_sign_up'      get '/sign_in_form' => 'users/sessions#sign_in_form', as: 'user_sign_in'    end  end  

and here is my controller

class Users::SessionsController < Devise::SessionsController    def sign_in_form    end  end  

I also have a .js.erb file for rendering the form, everything is working fine displayig the form it is just when it is submitted it doesnt do what i intended. Thanks in advance to anyone who can help me solve this problem.

ajax will_paginate drops the page to first when browser page refresh

Posted: 20 Dec 2016 05:45 AM PST

I'm beginner in RoR and I have app in which I use ajax with will_paginate like in #174 Pagination with AJAX - RailsCasts. All working fine, but I have issue such as after I select any will_paginate page and then refresh browser page will_paginate drops the page to '1'. I can't think that it is necessary to make that in case of refreshing of the browser page the will_paginate page still remained page selected early. Some my code:

_index_table.html.erb

<%= will_paginate @outdoor_advertisings, :param_name => 'order_page' %>    <table class="index_table">      ...    </table>  <%= will_paginate @outdoor_advertisings, :param_name => 'order_page' %>  

index.html.erb

<div id="index_table">    <%= render 'index_table' %>  </div>  

index.js.erb

$("div#index_table").html("<%= escape_javascript(render("index_table")) %>");  $(".ajax-progress").hide();  

controller action

class OutdoorAdvertisingsController < ApplicationController    def index        if !params[:order_page].present?        params[:order_page] = '1'      end        @outdoor_advertisings = OutdoorAdvertising.where(active: true)      .paginate(page: params[:order_page], per_page: 30)        respond_to do |format|        format.html         format.js      end       end  end  

outdoor_advertisings.js.coffee

$("body").on "click", "div#index_table .pagination a", ->    $(".ajax-progress").show();    $.getScript @href    return false  

server console log when index page open first time

Started GET "/outdoor_advertisings" for 127.0.0.1 at 2016-12-20 16:36:09 +0200  Processing by OutdoorAdvertisingsController#index as HTML  

server console log when select page

Started GET "/outdoor_advertisings?&order_page=3&_=1482244577710" for 127.0.0.1 at 2016-12-20 16:36:20 +0200  Processing by OutdoorAdvertisingsController#index as JS  Parameters: {"order_page"=>"3", "_"=>"1482244577710"}  

server console log when browser page refresh after will_paginate page '3' select

Started GET "/outdoor_advertisings" for 127.0.0.1 at 2016-12-20 16:36:24 +0200  Processing by OutdoorAdvertisingsController#index as HTML  

Rake task not sending mail rails

Posted: 20 Dec 2016 05:44 AM PST

I've written my first rake task in rails, I've set it up with the Heroku scheduler and it is getting run, however the mail isn't getting sent. My mail settings are fine as I'm using it for various other things, I would imagine it's a problem with my code in the rake task. Any help would be much appreciated.

lib/tasks/uncomplete_form.rake

desc "Remind users if they haven't completed quote form"  task uncomplete_form: :environment do      puts 'Reminding users of uncomplete quote form'      date = Date.parse('december 18 2016')      quickcontacts = Quickcontact.where(created_at: date.midnight..Time.now)          quickcontacts.each do |quickcontact|              next unless quickcontact.created_at > 1.hour.ago                   if quickcontact.p_p = nil                       QuickcontactMailer.uncomplete_form(@quickcontact).deliver                   end              end      puts 'done.'  end  

By running rake uncomplete_form I get

Reminding users of uncomplete quote form

done.

And running heroku run rake uncomplete_form I get

Reminding users of uncomplete quote form   Quickcontact Load (1.5ms)  SELECT "quickcontacts".* FROM "quickcontacts" WHERE ("quickcontacts"."created_at" BETWEEN '2016-12-18 00:00:00.000000' AND '2016-12-20 12:09:23.683977')  done.  

It doesn't seem to be picking up any quickcontacts - however if in the console I run:

date = Date.parse('december 18 2016')  

followed by

quickcontacts = Quickcontact.where(created_at: date.midnight..Time.now)  

It does find the expected contacts

Ruby on Rails - Count Entries on Scaffold

Posted: 20 Dec 2016 04:41 AM PST

In a simple Ruby on Rails applicaiton, I have a Scaffold called "Proposals" on which one of its columns is a string called "creationyear". I'm trying to count how many proposals have been created each year when the index page is loaded doing the following (in "proposals_controller.rb" file):

def index    @proposals = Proposal.all    @count2015 = Proposal.count(:all, :conditions => "creationyear = 2015")    @count2016 = Proposal.count(:all, :conditions => "creationyear = 2016")  end  

Somehow it is not working, since it gives me back on both variables the total number of entries on the scaffold.

Does anyone knows how to solve this one? I'm using Rails v4.2.6.

Thanks!

Rails commands not working on raspberry pi though it is installed

Posted: 20 Dec 2016 04:21 AM PST

I've been setting up a server on my Raspberry Pi but for some reason when I SSH into the pi I can use the rails commands and start the Rails server but whenever I go into the terminal of the Pi itself it says:

bash: rails: command not found  

Does someone know how to fix this? How can I make the rails command possible on the Pi terminal?

Thanks in advance!

No comments:

Post a Comment