Thursday, December 22, 2016

Logging raw SQL errors in Rake Tasks | Fixed issues

Logging raw SQL errors in Rake Tasks | Fixed issues


Logging raw SQL errors in Rake Tasks

Posted: 22 Dec 2016 07:41 AM PST

I'm using raw sql bulk updates (for performance reasons) in the context of a rake task. Something like the following:

update_sql = Book.connection.execute("UPDATE books AS b SET               stock = vs.stock,               promotion = vs.promotion,               sales = vs.sales               FROM (values #{values_string}) AS vs               (stock, promotion, sales) WHERE b.id = vs.id;")  

While everything is "transparent" in local development, if this SQL fails in production during the execution of the rails task (for example because the promotion column is nil and the statement becomes invalid), no error is logged.

I can manually log this with catching the exception, like below, however some option that would allow for automatic logging would be better.

begin  ...  rescue ActiveRecord::StatementInvalid => e          Rails.logger.fatal "Books update: ActiveRecord::StatementInvalid: "+ e.to_s  end  

cannot get controller instance variable with rspec

Posted: 22 Dec 2016 07:40 AM PST

I have simple controller:

class CreditLogsController < BaseController      def show      @account = Account.find_by_email(Base64.urlsafe_decode64(params[:id]))    end  end  

and here is the spec for it:

require 'rails_helper'

describe CreditLogsController, type: :controller do      describe 'GET #show' do      it 'responds with 200' do        create(:account)          get :show, params: {id: Base64.urlsafe_encode64('tes1@test.com')}, format: :html        puts "############# #{controller.instance_variable_get(:account)}"        expect(assigns(:account)).to eql('tes1@test.com')      end    end    end  

so the problems is, account in spec is always nil, in coverage file code from controller which assigns value to @account is showed as not covered and controller.instance_variable_get(:account) raises an error `account' is not allowed as an instance variable name. I have similar code in other spec and is working ok, so what I'm doing wrong?

Grouping an array of hashes

Posted: 22 Dec 2016 07:30 AM PST

so I'm working on a project where I have an array of hashes:

[{:year=>2016, :month=>12, :account_id=>133, :price=>5},   {:year=>2016, :month=>11, :account_id=>134, :balance=>3},   {:year=>2016, :month=>11, :account_id=>135, :balance=>0},   {:year=>2015, :month=>12, :account_id=>145, :balance=>4},   {:year=>2015, :month=>12, :account_id=>163, :balance=>11}]  

and basically I want to condense this down into the form:

{ 2016 => { 12 => { 1 => {:account_id=>133, :price=>5}},              11 => { 1 => {:account_id=>134, :balance=>3},                      2 => {:account_id=>135, :balance=>0}}},    2015 => { 12 => { 1 => {:account_id=>145, :balance=>4},                      2 => {:account_id=>163, :balance=>11}}}}  

but I'm having real trouble getting this done, at the moment I have:

data_array = data_array.group_by{|x| x[:year]}  data_array.each{|x| x.group_by{|y| y[:month]}}  

but this doesn't seem to work, I get an error saying no implicit conversion of Symbol into Integer.

Any help with understanding where I've gone wrong and what to do would be greatly appreciated.

how to use bootstrap-table Export extension

Posted: 22 Dec 2016 07:24 AM PST

I'm going absolutely mad over this. I'm still pretty new so bare with me if I'm sounding like an idiot =)

I've got a table I want to be able to export. I stumbled upon bootstrap-table at http://bootstrap-table.wenzhixin.net.cn/ and thought it was awesome, so I started using some of the stuff. pagination, search, other stuff working, great! but I can't figure out how to get the damn export extension to work! I've been at this for sooo long, searching forums, blogs, and the documentation on github. Anyway, so here's where I'm at.

I ran

npm install bootstrap-table  

then I added lines to my header, and a script to my body from this example: http://issues.wenzhixin.net.cn/bootstrap-table/#extensions/export.html and now my index.html.erb looks like this:

<head>  <meta charset="utf-8">  <link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css">  <link rel="stylesheet" href="../assets/bootstrap-table/src/bootstrap-table.css">  <link rel="stylesheet" href="../assets/examples.css">  <script src="../assets/jquery.min.js"></script>  <script src="../assets/bootstrap/js/bootstrap.min.js"></script>  <script src="../assets/bootstrap-table/src/bootstrap-table.js"></script>  <script src="../assets/bootstrap-table/src/extensions/export/bootstrap-table-export.js"></script>  <script src="//rawgit.com/hhurz/tableExport.jquery.plugin/master/tableExport.js"></script>  <script src="../ga.js"></script>  </head>  <body>      <div class="container">        <div id="toolbar">          <select class="form-control">              <option value="">Export Basic</option>              <option value="all">Export All</option>              <option value="selected">Export Selected</option>          </select>      </div>  <div class="booyah-box">  <table id="table"          data-toggle="table"         data-show-export="true"         data-pagination="true"         data-click-to-select="true"         data-toolbar="#toolbar"         data-url="../json/data1.json"         data-page-list="[10, 25, 50, 100, ALL]"         data-search="true"         data-show-pagination-switch="true"         data-show-columns="true"         data-minimum-count-columns="2"  >    <thead>    <tr>      <th data-field="state" data-checkbox="true">Select</th>      <th data-field="Project ID">Project ID</th>      <th data-field="Status">Status</th>      <th data-field="Project Type">Project Type</th>      <th data-field="Marker Strategy">Marker Strategy</th>      <th data-field="Traits">Traits</th>      <th data-field="Line">Line</th>      <th data-field="Line Origin">Line Origin</th>      <th data-field="Market Region">Market Region</th>      <th data-field="Governance Qualifier">Governance Qualifier</th>      <th data-field="New Start Year">New Start Year</th>      <th data-field="Initial Version Test Year">Initial Version Test Year</th>      <th data-field="Estimated Version Test Year">Estimated Version Test Year</th>      <th data-field="Last Location">Last Location</th>      <th data-field="Trait Code">Trait Code</th>      <th data-field="CMS Subtype/Type">CMS Subtype/Type</th>      <th data-field="NEIS">NEIS</th>      <th data-field="Root ID1">Root ID1</th>      <th data-field="Root ID2">Root ID2</th>    </tr>  </thead>      <tbody>      <% @tiprojects.each do |x| %>        <tr>          <td></td>          <td><%= x.pidtc %></td>          <td><%= x.status %></td>          <td><%= x.protype %></td>          <td><%= x.marker_strategy %></td>          <td><%= x.traits.upcase %></td>          <td><%= x.line %></td>          <td><%= x.origin %></td>          <td><%= x.market_region.upcase %></td>          <td><%= x.governance_qualifier %></td>          <td><%= x.new_start_year %></td>          <% if x.initial_vt_year == 9999 %>          <td>Not Applicable</td>          <% else %>          <td><%= x.initial_vt_year %></td>          <% end %>          <td><%= x.estimated_vt_year %></td>          <td>NA</td>          <td><%= x.trait_code %></td>          <td><%= x.cms_subtype %></td>          <td><%= x.neis %></td>          <td><%= x.root_pidtc1 %></td>          <td><%= x.root_pidtc2 %></td>        <% end %></tr>      </tbody>    </table>  <br />  <% if current_user.admin? %>  <%= link_to "Download Template Upload", download_csv_path %>  <br />  <%= form_tag import_ti_projects_path, multipart: true do %>    <%= file_field_tag :file %><br />    <%= submit_tag "Upload New Projects" %>  <% end %>  <% end %>  </div>  <script>  var $table = $('#table');  $(function () {      $('#toolbar').find('select').change(function () {          $table.bootstrapTable('destroy').bootstrapTable({              exportDataType: $(this).val()              showExport: 'true'            });      });  })    </script>    </body>  

Restrict a visitor submit the form if it was already submitted by him

Posted: 22 Dec 2016 07:21 AM PST

I want to restrict a visitor to submit the form more than once, and the only way of doing, as I think, is cookies. In my controller I create a cookie:

class RatingsController < ApplicationController    require 'securerandom'    before_action :session_cookie      def create      @rating = Rating.new(rating_params)      @rating.save      render json: { rating: @rating.casino.average_rating.to_f.round(2) }, status: 200    end      private      def rating_params      params.require(:rating).permit(:score, :casino_id)    end      def session_cookie      cookies[:name] = { value: SecureRandom.base64, expires: Time.now + 3600}    end    end  

The form, I'm using - is submitting by clicking on a star(it's a 5 star rating, and I use ajax to submit it). And now, how to restrict a visitor to submit the form again, using that cookie? The first idea was to add a column to db and save a cookie there, and then use validation, to check uniqueness of cookie, but I don't know, if this is a good idea.

Sandboxing JS Execution within Rails App

Posted: 22 Dec 2016 07:10 AM PST

Background

I'm building a Ruby on Rails application that allows a user to upload a custom JavaScript that will be executed on the server. This custom script is used to define a field on the API response. The following list describes the sequence of events.

  1. User sends HTTPS request to application API via POST
  2. API controller formulates JSON response
  3. User's Script is executed and the output is saved as a field on the JSON response
  4. API response is sent

The method below is used for script execution. script_body contains the user's custom JavaScript and is saved in the DB as a text field on an object that belongs to the User.

def run_script    begin      Timeout::timeout(2) { script_output = ExecJS.exec(script_body).to_s }    rescue => e      logger.info  "Script failed: #{e.message}"      script_output = "(Script failed with the following error: #{e})"    end  end  

Problem

I'm wondering how best to sandbox the execution of the JS script to mitigate security implications of executing user scripts on the server. I would like to know the recommended approach for:

  • Ensuring that the JS script cannot access any files on the server
  • Prevent the script from accessing the Rails application or DB
  • Protect against any other malicious activity (I'm not an expert so please forgive the lack of detail)
  • Maintain reasonable performance (needs to execute within an API call)

Additional Info

I have tried to find some examples of sandboxing JS execution within Ruby applications and haven't found much. I have looked at the following gem (https://github.com/tario/shikashi). However, this seems to be a sandbox for Ruby code only. I'm concerned that I would provide privileges for ExecJS.exec to execute and then the JS would be able to do whatever it wants. I'm not sure this would be the best approach.

Ruby + WebDriver > Selecting from dropdown in Angular 1

Posted: 22 Dec 2016 07:15 AM PST

I have the following HTML:

<div class="modal-content" uib-modal-transclude="">     <form class="ng-pristine ng-scope ng-invalid ng-invalid-required ng-valid-maxlength ng-valid-leftover-text" pb-submit="form.$valid && ctrl.submit()" name="form" novalidate="">       <div class="modal-header">         <div class="modal-body">           <!-- ngIf: authentication.user.isCustomer -->             <div class="form-group ng-pristine ng-invalid ng-invalid-required ng-valid-maxlength" ng-form="">                <div class="form-group ng-pristine ng-invalid ng-invalid-required" ng-form="">                  <label class="control-label" for="pill">Pill</label>                    <select id="pill" class="form-control ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" required="" ng-disabled="ctrl.readOnly" ng-options="i.name as i.name for i in ctrl.pills" ng-model="ctrl.group.pill">                     <option value="?" selected="selected"/>                     <option label="Red Pill" value="Red Pill">Red Pill</option>                     <option label="Blue Pill" value="string:Blue Pill">Blue Pill</option>

I am using Selenium WebDriver with Ruby and several gems, including Capybara. I am trying to choose the Red Pill (obviously) via the dropdown selector. So far, I have tried the following:

find('#pill').find(:xpath, "//*[@id='pill']/option[2]").select_option    find(:xpath, "//*[@id='pill']/option[2]").select_option    select_by(:value, 'string:Red Pill')    select('Red Pill', from: 'pill')    find('option', :text => 'Red Pill').click    find(:xpath, "//div[contains(text(), 'Red Pill')]/..").click

Ruby accepts the above commands (i.e. the syntax is OK), and even engages the dropdown (when I click on it, all the options are displayed), but it doesn't seem to know what to do and simply moves on to the next step without making any selection or otherwise failing.

My suspicion is that this is all because of Angular 1, such that this is not technically a dropdown but something else. Any thoughts?

pass value from view to controller action

Posted: 22 Dec 2016 06:28 AM PST

I made a table in rails using

<table class="table_box">        <%= table_head([            {text: "wanted",       width: "30%"},            {text: "Skill",              width: "30%"},            {text: "Duration (In months)", width: "30%"},            {text: "Proficiency",      width: "10%"}])%>       <tbody id="skill">     <% skills.each do |skill| %>          <tr class="<%= cycle("tr_box","tr_box odd",:name=>"details")%>">          <% contains_skill = user_skills.include? skill               indeex = user_skills.index(skill) if contains_skill           has_experience = (indeex ? user_experience[indeex] : '')           has_proficiency = (indeex ? user_proficiency[indeex] : '')        %>        <%= table_row([            {:text=>check_box_tag("checkbox[]",value = "1",checked = contains_skill)},            {:text=>skill},            {:text=> (number_field_tag 'quantity', has_experience, in: 1...5)},            {:text=> (select_tag "credit_card", options_for_select([ '','Expert', 'Average','Beginner' ], has_proficiency))},           ])%>    </tr>    <% end %>          <div class="clear"></div>        </tbody>    </table>  

now i want all the parameets(values of table) to go into my controller so i can process them , i tried making a button

<%= button_to "New", action: "update" %>  

but did't help. please tell me how can i get the values of table into the controller.

Extract objects by their properties from list of class names in ruby

Posted: 22 Dec 2016 07:07 AM PST

I have a list of Class names: obj_list = ["Fruit", "Vegetable"] and I need to iterate over them and find all object that have color attribute set to red (assuming that both Fruits and vegetables has this attribute).

How to calculate points using SQL not ruby

Posted: 22 Dec 2016 06:17 AM PST

I have a rake task in my rails app which calculate bonuses:

namespace :all_bonus do   desc "all given bonuses"   task given_bonuses: :environment do     points = 0     Bonus.find_each do |bonus|       points += bonus.points     end       puts Bonus.count     puts points   end  end  

Find each method is loaded memory and I want to change it using SQL. How can I do it?

Active Admin Editor gem shows blank form like text area instead od editor (error0

Posted: 22 Dec 2016 05:33 AM PST

In active admin editor when i put ", as: :html_editor" it shows blank big form like text area instead of editor i have used github of ejholmes/active_admin_editor . please request you to provide solution ?

adding optional parameters in paths dynamically ruby on rails

Posted: 22 Dec 2016 05:38 AM PST

I have routes like this:

resources :lesson_plans do     resources :videos  end  

and also

resources :subjects do    resources :lesson_plans do    resources :videos   end  end  

Now I want to create dynamic paths and adding conditional parameters to them.

If I have url like:

http://localhost:3000/teacher/katherine-fleming/subjects/3/lesson_plans/3  

the path is now:

http://localhost:3000/teacher/katherine-fleming/subjects/3/lesson_plans  /3/videos/new  

but if I have url like this:

http://localhost:3000/teacher/carmel-cynthia/lesson_plans/68  

the path is:

http://localhost:3000/teacher/carmel-cynthia/lesson_plans//videos/new.68  

but it should be as its my requirement:

http://localhost:3000/teacher/carmel-cynthia/lesson_plans/68/videos/new  

the code I am trying is:

Code:

<% subject_path = params[:subject_id].present? ? 'subject_' : '' %>  <% subject_var = params[:subject_id].present? ? @subject : '' %>  

Button:

<%= link_to '+ New Video', send("new_teacher_teacher_#  {subject_path}lesson_plan_video_path", @teacher, subject_var, @lesson_plan),   remote: true, class: "btn btn-info plans-items-btn" %>  

Any more better way to cope with it. basically subject_id is what I have optional for both cases.

Can't test controller render due to ActiveRecord::StatementInvalid:error

Posted: 22 Dec 2016 05:21 AM PST

Ok, I have this controller code:

def create      @foo = Foo.new(user: User.new(user_params))      if @foo.save        redirect_to foos_path      else        render :new      end  end  

And I would like to test if it re-renders the new page when the user email is invalid. To do that, I created this test:

it "should re-render the new template" do      post :create, params: { user: attributes_for(:user, email: "abc.com") } }      expect(response).to render_template(:new)  end  

However, the test is failing due to this error:

 Failure/Error: if @professor.save     ActiveRecord::StatementInvalid:     PG::NotNullViolation: ERROR:  null value in column "user_id" violates not-null constraint     DETAIL:  Failing row contains (260, null).     : INSERT INTO "foos" DEFAULT VALUES RETURNING "id"  

The Foo table has a

t.belongs_to :user, null: false, index: true  

so that it does not add a foo without a user.

I think this error is actually a desired behavior, since it prevents the foo to be saved without a user and the user cant be saved with an invalid email. But I still need to test it, so am I testing it wrongly? How can I do that? Is there something missed?

Thanks in advance!

ActiveResource: how to handle namespaced routes?

Posted: 22 Dec 2016 03:48 AM PST

I have an application with routes like:

namespace :api do    namespace :v1 do      resources :things    end  end  

What's the right way to connect to this application's api/v1/things route with ActiveResource?

Right now it looks a whole lot like I will have to implement custom_method_collection_url but that feels like a hack - is it the only way?

Extend view with decorators

Posted: 22 Dec 2016 04:52 AM PST

I am using a ActiveJob object to generate a PDF with wicked_pdf. To do this I need to extend some view things to be able to do this is from a Job object:

view = ActionView::Base.new(ActionController::Base.view_paths, {})  view.extend(ApplicationHelper)  view.extend(Rails.application.routes.url_helpers)  view.extend(Rails.application.routes.url_helpers)  

This is all working fine, the PDF is created. But in the view I use decorators like this:

- decorate invoice do |decorates|    = decorates.title  

And that is not working, probably because the object is not aware of these decorators, which are just PORO objects. So I guess I need to extend them too so they can be used here. How can I extend them? They are located in app\decorators

Edit: The decorates method comes from a helper method:

module ApplicationHelper    def decorate(object, klass = nil)      unless object.nil?        klass ||= "#{object.class}Decorator".constantize        decorator = klass.new(object, self)        yield decorator if block_given?        decorator      end    end  end  

And that helper method loads the correct decorator object:

class InvoiceDecorator < BaseDecorator    decorates :invoice  end  

Which inherits from Base decorator:

class BaseDecorator    def initialize(object, template)      @object = object      @template = template    end      def self.decorates(name)      define_method(name) do        @object      end    end  end  

Sorting posts based on the most liked in Rails

Posted: 22 Dec 2016 05:25 AM PST

I am trying to have two tabs, one for the most recent posts and the other is for the most liked posts. However, I am really stuck of how to get my post sorted by the most liked(voted). I did use acts_as_votable gem to get the voting system part into the website. I am new to Rails, let me know if what more details do you need to help out,thanks.

Aspect ratio of a div depending on header picture?

Posted: 22 Dec 2016 03:28 AM PST

I have a welcome page which has a header background with position absolute. Im using the navigation bar which is transparent on top. My issue is now that all the elements of the page are on the header background and I want only certain parts on the header picture. So I thought implementing a div which changes with the same ratio as the header picture(1920px x 1080px). I am trying this by using:

CSS

.header {    display: inline-block;    width: 100%;    padding-bottom: 56.25%;  }    .header_picture {      width: 100%;      position: absolute;      top: 0;      z-index: -1;  }  

HTML

<%= image_tag("header.jpg", alt: "header kinky couple", :class => "header_picture") %>  <div class="header">      <h1>Erfüllen Sie sich Ihre Erotikreise</h1>        <div class="welcome_search">          <%= search_form_for @search, url: search_path do |f| %>              <div class="form_wrapper">                  <%= text_field_tag :search, params[:search], placeholder: "Wohin?", class: "formfield" %>                  <%= text_field_tag :start_date, params[:start_date], placeholder: "Check-In", class: "formfield" %>                  <%= text_field_tag :end_date, params[:end_date], placeholder: "Check-Out", class: "formfield" %>                  <%= f.select :persons_gteq, [["2",2], ["3",3], ["4",4], ["5",5], ["6+",6]], class: "formselect",                  prompt: "Personen" %>              </div>                <div class="button_wrapper">                  <%= f.submit "Suchen", class: "formbutton" %>              </div>            <% end %>      </div>  </div>  

Unfortunately it does not change the dimensions with the same ratio as the header background. How can I implement this? Is there a easier solution to accomplish this? The height of the navigationbar depends also from the size so its scaling as well. I know that I have to use ($height / $width) * 100% to figure out padding-bottom. But it scales different.

enter image description here

Rails 5 redirect_back not behaving as expected locally

Posted: 22 Dec 2016 02:47 AM PST

Ive recently upgraded an application to Rails 5 and subsequently updated all references to redirect_to :back, to redirect_back.

This seems to be behaving as expected in production, when running the app locally, it redirects to the url of the last image that was rendered on the page. While this is not really an issue I wondered if anyone has encountered anything similar and has any solutions?

Access nested attributes in before save call back

Posted: 22 Dec 2016 02:40 AM PST

I have following relationships

class Customer < ActiveRecord::Base    has_many :applications, :dependent => :destroy     before_save: validate_presence_priority_id  end  

and in my Customer controller I have

def customer_params  params.require(:customer).permit(:name, application_attributes: [:duration, :priority_id, :_destroy])  end  

Now I want to do something like this

def validate_presence_priority_id((attributes))      if !attributes['priority_id'].present?        attributes.merge!({:_destroy => 1})      end  end  

so basically I want to check if priority_id is not present then just add destroy attribute. How can I achieve this?

Rails internationalization if check not working

Posted: 22 Dec 2016 03:00 AM PST

I have a rails app and working with two languages.

Interestingly, when I check the following in main.html.erb;

MYLOCAL <%= I18n.locale == "en" %>|<%= I18n.locale %>  

outputs;

false|en  

Why would that happen ?

Rails controller manually sanitize parameters

Posted: 22 Dec 2016 03:13 AM PST

Suppose my views need to pass some params that are absolutely not related to a model. What are the best ways to sanitize the input in the controller ?

Eg - Validate inclusion of a parameter in a string array : display_type param that sets whether search results are displayed on a map or in a list, as cards, etc., but only a few are defined and available - Validate the type/numericality of some parameter (eg params[:page] should be an integer or fallback to default page 0

Currently I'm using something like

def validate_xxx_param    if ['map', 'card'].include?(params[:display_type))      ...    else      ...    end  end  

But is there a cleaner/better OOP way of doing that ?

Getting shared path in controller with Rails and Capistrano

Posted: 22 Dec 2016 02:19 AM PST

I have an upload system that performs several conversion operations on uploaded files (needs the real file paths to do them) and then stores paths of the resulting files.

Those files will be accessed later to create a zip file (again real path needed)

The problem with Capistrano is obviously when I store the file path using Rails.root.join('public', 'uploads', 'designer_user_uploaded') and then try to create my zip file like 10 days later and the release has changed, the stored file path no longer points to the correct location.

My directory is in the linked dirs for Capistrano. So the files are not lost but they just can't be retrieved anymore.

I'm not sure how I should handle this. I think it would be easy to solve by just doing something like File.join(shared_path, 'public', 'uploads', 'designer_user_uploaded') but I can't find how to get the shared path from controllers. Also this might not work in development.

I'm on Rails 4.2.6

 output_folder = Rails.root.join('public', 'uploads', 'designer_user_uploaded')            FileUtils.mkdir_p(output_folder) unless File.directory?(output_folder)              file_name = sanitize_filename(Time.now.to_s + "_" + SecureRandom.uuid)            original_file_path = output_folder.join(change_file_extension(file_name, ext))            designer_file_path = ext == '.ai' || ext == '.eps' ?                output_folder.join(change_file_extension(file_name, '.svg')) : output_folder.join(change_file_extension(file_name, ext))              if ext == '.ai' || ext == '.eps'              copy_file(file.path, original_file_path)              copy_file(svg_path, designer_file_path)                @response[:original_file_path] = original_file_path              @response[:designer_file_path] = designer_file_path              @response[:file_name] = file_name + '.svg'              @response[:file_type] = "svg"              @response[:colors] = get_image_colors(original_file_path)                # Store created file paths for future access              @up = UserUpload.create(designer_path: designer_file_path, original_path: original_file_path)              puts @up.id              @response[:file_id] = @up.id            else              copy_file(file.path, designer_file_path)                @response[:original_file_path] = nil              @response[:designer_file_path] = designer_file_path              @response[:file_name] = file_name + ext              @response[:file_type] = ext == '.svg' ? 'svg' : "image"              @response[:colors] = get_image_colors(designer_file_path)                # Store created file path for future access              @up = UserUpload.create(designer_path: designer_file_path)              puts @up.id              @response[:file_id] = @up.id            end              # Embroidery conversion            is_embroidery = params[:is_embroidery].to_s.downcase == 'true'            if is_embroidery && (ext == '.svg' || ext == '.ai' || ext == '.eps')                embroidery_file_name = "embroidery_#{file_name}.svg"              embroidery_path = output_folder.join(embroidery_file_name)                Embroidery::EmbroideryConversionJob.perform_async(original_file_path, embroidery_path, @up)              @response[:designer_file_path] = embroidery_path              @response[:file_name] = embroidery_file_name              @response[:file_type] = "embroidery"            end              @response[:output_url] = '/uploads/designer_user_uploaded/'            file.close(true)  

Update div's value, using ajax call

Posted: 22 Dec 2016 02:05 AM PST

I have a rating system in my app, and a <div> element with average rating in it. I need to update the average rating value, when I click on a star(it creates a new rating in a db). This is my view for index page, where I use rating:

<h1>List of casinos</h1>    <div class="casinos-list">    <% @casinos.each do |casino| %>      <div class="casino-item">        <p class="casino-name"><%= link_to casino.name, casino %></p>        <p class="casino-description"><%= casino.description %></p>        <ul class="rating">          <% form_id = "casino_#{casino.id}_rating" %>          <%= form_for casino.ratings.build, html:              { id: "casino_#{casino.id}_rating", class: 'star_rating_form' } do |f| %>            <%= f.hidden_field :casino_id %>            <%= f.hidden_field :score, id: "#{form_id}_stars", class: 'star-value' %>          <% end %>          </ul>        <div id="<%= "average_rating_#{form_id}" %>" class="average-rating" data-rating="<%= casino.id %>"><span><%= casino.average_rating.to_f.round(2) %></span></div>        <div id="<%= "rate_#{casino.id}" %>" class="rateit" data-rateit-mode="font">        </div>      </div>    <% end %>  </div>  

and my application.js:

$(document).on('turbolinks:load', function () {      $('.rateit-reset').remove();      $('.rateit-hover').click(function () {      var rating = $(this).parents().attr('aria-valuenow');      var float_number = parseFloat(rating);      var rating_form_input = $(this).parents().parents('.casino-item').children('.rating').children('.star_rating_form').children('.star-value');      var form_id = $(this).parents().parents('.casino-item').children('.rating').children('.star_rating_form').attr('id');      rating_form_input.val(float_number);        $.ajax({        type: 'post',        url: $('#' + form_id).attr('action'),        data: $('#' + form_id).serialize()      })    })    });  

I tried to do something like this: $(this).parents().parents().parents('.casino-item').children('.average-rating').children('span').load(location.href + ' .average-rating');, but it created a new element near existing one. As I understand, I need to make one more ajax call. I tried to do it like this:

function updateRating () {    var $target = $('.average-rating');    $.ajax({        url: '/casinos/',        dataType: 'json',        type: 'get',        success: function(data) {          $target.html(data['response'])        }      }    );  }  

but it gives me all my casinos. I'm confused, how does url should look like in an ajax call? Or maybe I'm missing something else? Thanks in advance.

rails route dynamically update with dynamic value

Posted: 22 Dec 2016 01:51 AM PST

I want dynamic url with dynamic value, lets e.g http://example.com/sample , here sample will be dynamic which will fetch from database. In case of user type /abcdxysz etc then it will show 404 as rails default.

I am trying

get ':dynamic_template' , to: 'pages#show' , as: :dynamic_temp, constraints: DynamicConstraint  

but its not rendering other site's pages correctly like /about or /contactalso redirect other.

I want it dynamic value wise render. Id in the table the values are sample, sample1 if user type http://example.com/sample then it will open something like that.

How to search for the fields of the parent model through child model in polymorphic association

Posted: 22 Dec 2016 02:01 AM PST

class Book < ActiveRecord::Base    belongs_to :owner, polymorphic: true  end    class User < Active record::Base    has_many :books, as: :owner  end  

Now the Book has three fields - name, owner_id and owner_type. Now I need to search for the name of the user through books.

Something like this ..

Book.includes(:user).where("user_name LIKE ?","bla")  

can anyone help me this?

we find all contract of a user and all jobs of contract of that particular user

Posted: 22 Dec 2016 03:27 AM PST

I have two models one is User and another is Contract. These are my models

  class User < ApplicationRecord       has_many :user_jobs ,dependent: :destroy       has_many :contracts ,through: :user_jobs    end      class Contract < ApplicationRecord       has_many :user_jobs ,dependent: :destroy       has_many :users ,through: :user_jobs           end    class UserJob < ApplicationRecord      belongs_to :user      belongs_to :contract    end  

we have to find all unique contracts of a user

How to check the existence of a key in params in Rails?

Posted: 22 Dec 2016 04:51 AM PST

I'm still trying to make my second feed work but it doesn't quite work at the moment.

I struggled with this error and i'm wondering what i'm doing wrong so if someone could explain me that would be pretty good.

users_controller.rb:

@user = User.find(params[:id])    @microposts_second = @user.microposts.paginate(page: params[:page] + 1)  end  

show.html.erb

<% if @user.microposts.any? %>    <h3>Microposts (<%= @user.microposts.count %>)</h3>    <ol class="microposts">      <%= render @microposts_second %>    </ol>    <% end %>  </div>  

That's what giving me the error when I viewed it:

undefined method `+' for nil:NilClass

NoMethodError in Users::RegistrationsController#create in rails 5

Posted: 22 Dec 2016 01:09 AM PST

How can Solve this problem

can any one help me how can i fix this issue i am tired and waste approx 3 days but cannot solve this probelm open above link to see full error

Why I get `ActiveRecord::NoDatabaseError: Unknown database` error when trying to use numbers and underline in database name?

Posted: 22 Dec 2016 02:45 AM PST

I am using ruby-2.2.4, Rails 4.2.5 and MySQL 5.7.16 with gem mysql2 in my Ruby on Rails application. I have created database with name 123_4 and set database name in /config/database.yml.

Why I am getting error ActiveRecord::NoDatabaseError: Unknown database '1234' when trying rake db:migrate?

If I try to run rake db:create database with name 1234 will be created.

If I use 123_abc4 for database name everything is fine.

my database.yml content:

production:      adapter: mysql2      database: 123_4      host: localhost      username: user      password: "pass"      encoding: utf8  

Is there any gem specifically for Paytm integration?

Posted: 22 Dec 2016 01:29 AM PST

How to integrate Paytm integration alone, has Paytm exposed their APIs or has anyone created a gem for this?

I couldn't find anything except this, and this one isn't having any proper documentation!

Please assist!

No comments:

Post a Comment