Friday, April 8, 2016

Rails, static page for newest model | Fixed issues

Rails, static page for newest model | Fixed issues


Rails, static page for newest model

Posted: 08 Apr 2016 06:51 AM PDT

In my rails app I have a model called "Gamesession", this will take some variabels to generate different configurations to a game(i'm playing in real life) each time I play. So I want a static page called play.html.erb to always be the place where the newest "active" session is. Right now I'm deleting all the previous sessions everytime I make a new. So that I can use the gamsession#index. Is there a better way to only have one "active" gamesession on the same page(play.html) each time? Please explain in detail if you have the time, I'm very new at rails. Thank you!

If checked then disabled form

Posted: 08 Apr 2016 06:29 AM PDT

I have these code:

<div class="nested-fields">    <div class="row">      <div class="col-sm-4">        <div class="form-group">          <%= f.input :start_work, as: :date, start_year: Date.today.year - 20,                                              end_year: Date.today.year, ignore_day: true,                                              order: [:month, :year],                                              input_html: { class: 'form-control' },                                              label: 'Start work period' %>        </div>          <div class="form-group">          <%= f.input :is_current, label: 'Currently work here', input_html: { class: 'current' } %>        </div>      </div>        <div class="col-sm-4">        <div class="form-group">          <%= f.input :end_work, input_html: {class: 'end_work'}, as: :date, start_year: Date.today.year - 20,                                              end_year: Date.today.year, ignore_day: true,                                              order: [:month, :year],                                              input_html: { class: 'form-control' },                                              label: 'End work period' %>        </div>      </div>    </div>  </div>    <script>    $(document).ready(function() {      // experience current work      $(".current").each(function() {        $(this).click(function() {          var isCurrent = $(this).prop("checked");          if (isCurrent == true) {            $(this).closest('.form-group').next('.form-group').find('.end_work').prop("disabled", "disabled");          }          else {            $(this).closest('.form-group').next('.form-group').find('.end_work').prop("disabled", false);          }        });      });    });  </script>  

However, I can't disabled my end_work input when the current box checked. I think I missed the target class or something on Javascript. Any helps will be great!

Elasticsaerch rails - can't search for mac extensions

Posted: 08 Apr 2016 06:33 AM PDT

I have setup elastic search rails with the 'elasticsearch-model', 'elasticsearch-rails' gems.

I am trying to search for these attachments by their content. It works well when I have an indexed PDF, Word, plain text, or a plefora of other formats. But it does not work when I index a mac format, e.g. .pages, .keynote and .numbers files.

I made sure that mac files get indexed, but it feels like they are not indexed properly. When I look at raw index data for a .word file vs .pages file, they both have their respective attachment fields populated as base64 representation of the document content. It seems like for the mac extensions, however, this base64 representation isn't accurate.

My index model definition:

settings index: { number_of_shards: 3 } do   mappings do     indexes :filename     indexes :uploaded_by     indexes :project_id, index: :not_analyzed     indexes :attachment, type: 'attachment'   end  end    def as_indexed_json(options={})    self.as_json({      only: [:project_id, :filename, :uploaded_by, :attachment],      methods: [:attachment]    })  end  

My attachment method:

def attachment    if url      key = url.sub("https://s3.amazonaws.com/#{ENV['BUCKETNAME']}/", "")      content = AWS.s3.buckets[ENV['BUCKETNAME']].objects[key].read        Base64.encode64(content)    end  end  

The file first gets uploaded to s3 (since client side sends it there directly), then read by the server from s3 to get indexed. this is a proof of concept code only, future dev will upload from client to server, index, then upload to s3, then delete from server.

E.S version: "1.7.1", Lucene version: "4.10.4"

How to validate presense of a value based on an API call

Posted: 08 Apr 2016 06:49 AM PDT

I've got a model @record_request that takes in a unique identifier and saves it to the database - the model can be later used to fire a bunch of API requests off to an external database to do it's work.

Thing is, I don't want the user to be able to save the value in the Rails app, if it can't be queried in the remote database.

I've tried creating validations and creating Rspec tests, but all of them require my @current_user variable with all the api_token and referesh_token and other OmniAuth goodies needed to make an autenticated API call...

So I'm kind of stumped. Where is the best practice place to put a validation rule of this kind.

I'm thinking I'll have to put something in my controller on :create that makes the call there and raises errors/flashes that way... but then it seems like I've got a load of code on my controller, and I've fallen for a fat controller anti-pattern, no?

What is the best practice?

How add different css styles for date_select field?

Posted: 08 Apr 2016 06:32 AM PDT

I have select list for input birthday

<%= f.date_select :birthday, {include_blank: true, start_year: Time.now.year - 70} %>  

I need add following css style in date_select. I cant undestand, how add different css classes? Can you help me, please?

<select class="form-control_medium" tabindex="-1" role="chzn_select" style="display: none;">  <option value="">Month</option>  <option value="1">Yanuary</option>  <option value="2">February</option>   ....................................  </select    <div class="chosen-container chosen-container-single chosen-container-single-nosearch" style="width: 150px;" title=""><a class="chosen-single" tabindex="-1"><span>Month</span><div><b></b></div></a><div class="chosen-drop"><div class="chosen-search"><input type="text" autocomplete="off" readonly="" tabindex="3"></div><ul class="chosen-results"></ul></div></div>  

Users, form and tasks association rails

Posted: 08 Apr 2016 06:17 AM PDT

I have an app allowing a user to fill a form (named "checklist") and then have a list of tasks he will have to do. The tasks (named "advices") are related to the answers that the user gave in the form. For example, if a question is "have you cooked dinner ?" and the user answers "no", then an advice "go cook dinner" will be displayed.

Once a advice is done, the user can mark it as completed. Advices are the same for all users. They already are created in the app by admin.

So users have a checklist, checklist belongs to a user.

The problem I encounter is : when a user marks an advice as completed, it is marked as completed for all users. That should not be.

I am not really sure how to fix this. Associations "Has-many", and "Belongs_to" between advices and users should not work since the user does not create the advices ?

I am new to rails so I would be happy if someone could help. Note that I use Devise to manage users.

Schema :

ActiveRecord::Schema.define(version: 20160407143608) do      create_table "advices", force: :cascade do |t|      t.string   "name"      t.text     "content"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "category_id"      t.boolean  "status"      t.string   "linkname1"      t.text     "link1"      t.text     "link2"      t.string   "linkname2"      t.text     "link3"      t.string   "linkname3"      t.integer  "ref"      t.boolean  "completed"    end      create_table "categories", force: :cascade do |t|      t.string   "name",       null: false      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end      create_table "checklists", force: :cascade do |t|      t.boolean  "facebook"      t.boolean  "twitter"      t.boolean  "linkedin"      t.boolean  "viadeo"      t.boolean  "instagram"      t.boolean  "community"      t.boolean  "cms"      t.boolean  "seo"      t.boolean  "crowdfunding"      t.datetime "created_at",   null: false      t.datetime "updated_at",   null: false      t.integer  "user_id"    end      add_index "checklists", ["user_id"], name: "index_checklists_on_user_id"      create_table "users", force: :cascade do |t|      t.string   "email",                  default: "", null: false      t.string   "encrypted_password",     default: "", null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,  null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                          null: false      t.datetime "updated_at",                          null: false    end      add_index "users", ["email"], name: "index_users_on_email", unique: true    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true    end  

Models :

class Advice < ActiveRecord::Base      belongs_to :category  end    class Checklist < ActiveRecord::Base      belongs_to :user  end    class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable    has_many :checklists  end  

where to put test gems in rails4

Posted: 08 Apr 2016 06:13 AM PDT

I've seen different sources where the test gems are placed in other groups of the gemfile. For example in one tut the factory_girl_rails is in group :development, :test and in another it's in group :test.

Is there an easy way to decide where to put the following gems?

factory_girl_rails  launchy  jasmine  guard-rspec  capybara  shoulda  

how to count messages for mailboxer gem

Posted: 08 Apr 2016 05:54 AM PDT

hi am using merit to grant badges to users that send messages through mailbox. i have setup mailboxer and its working fine in which users can have a conversation and send messages to each other. from that i added merit to grant badges to users that send message like this

grant_on 'messages#create',  badge: 'Engraved Glass', to: :user do    |message|      message.user.messages.count >= 50  end  

but when ever i create new message i get this error

undefined method `user' for true:TrueClass  

but when its sending message on a old conversation it doesnt throw this error

Unable to render inline attachments in ActionMailer

Posted: 08 Apr 2016 06:34 AM PDT

I'm trying to render inline images in a standard ActionMailer view using the approach outlined here Rails attachments inline are not shown correctly in gmail.

My code in my mailer:

attachments.inline["sample.png"] = {    mime_type: "image/png",    encoding: "base64",   # Including this line causes byte sequence error    data: File.read('public/sample.png')  }  

In mail view:

image_tag(attachments["sample.png"].url)  

Gives the familiar ruby UTF-8 byte sequence error:

invalid byte sequence in UTF-8

To get around this I tried the following:

attachments.inline["logo.png"] = {        mime_type: "image/png",        data: Base64.encode64(File.read('public/logo.png'))       }  

and also

attachments.inline["logo.png"] = File.read('public/logo.png')  

Using the same image_tag syntax shown above.

Both of these resolve the UTF error, but I'm left with this nonsensical URL in the view:

<img src="cid:5707a64ededbc_7bd83ffd648601e029875@localhostname.mail">

The PNG image is valid and renders properly in a standard HTML view. I'm using Rails 4.2.5 with Ruby 2.2.4

EDIT

This works:

Mailer:

attachments.inline["cape.png"] = {    mime_type: "image/png",    # encoding: "base64",    content: Base64.encode64(File.read(Rails.root.join("public/", "cape.png")))  }  

View:

= image_tag "data:image/png;base64,#{attachments['logo.png'].read}"  

Very awkward, however, and I'm still wondering why the conventional approach doesn't work.

Ruby on Rails prod preprod: not the same behavior in the treatment of version

Posted: 08 Apr 2016 06:34 AM PDT

please i need help i use this code for loading viewer

    def mask_url(options = {})  mask_host = Gaston.amazon.cloudfront.host  if self.company    mask_foldername = self.company.mask.present? ? "#{self.company.mask.name}" : "mask_boxes"    if self.try(:domain).try(:player_version).try(:name).to_f >= 4.4      "#{mask_host}/players/#{self.try(:domain).try(:player_version).try(:fullversion)}/thirdparties/players/#{player_type.try(:name)}/config/#{mask_foldername}/mask.json".downcase    else      "#{mask_host}/players/#{self.try(:domain).try(:player_version).try(:fullversion)}/lib/players/#{player_type.try(:name)}/config/#{mask_foldername}/mask.json".downcase    end  else    if self.try(:domain).try(:player_version).try(:name).to_f >= 4.4        "#{mask_host}/players/#{self.try(:domain).try(:player_version).try(:fullversion)}/thirdparties/players/#{player_type.try(:name)}/config/#{mask_foldername}/mask.json".downcase    else      "#{mask_host}/players/#{self.try(:domain).try(:player_version).try(:fullversion)}/lib/players/#{player_type.try(:name)}/config/#{mask_foldername}/mask.json".downcase    end  end  end  

the problem in preprod i choose player profile = 4.4 and it works

    Request URL:https://cdn-     preprod.trylive.com/players/4.4.4855/thirdparties/players/viewer/flash/vi  ewer.swf      Request Method:GET      Code:200 OK (from cache)  

in prod when i choose player 4.4,normally for 4.4 the path is ..../4.4.4855/thirdparties/players/viewer/flash/viewer.swf but i get this error

   Request URL:https://cdn.trylive.com/players/4.4.4855/lib/players/viewer/flash/viewer.swf    Request Method:GET    Status Code:404 Not Found  

ERROR: Failed to build gem native extension

Posted: 08 Apr 2016 05:28 AM PDT

installed PostgreSQL on my ubuntu system and when i try to run bundle install i am getting the following error.

Is there any way to run the command and install all the necessary gems

-- gem install pg -v '0.18.4'  Building native extensions.  This could take a while...  ERROR:  Error installing pg:      ERROR: Failed to build gem native extension.        current directory: /home/mink7/.gem/ruby/2.3.0/gems/pg-0.18.4/ext  /home/mink7/usr/local/2.3.0/bin/ruby -r ./siteconf20160408-15866-1siay0w.rb extconf.rb  checking for pg_config... yes  Using config values from /usr/bin/pg_config  You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.  You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.  checking for libpq-fe.h... no  Can't find the 'libpq-fe.h header  *** extconf.rb failed ***  Could not create Makefile due to some reason, probably lack of necessary  libraries and/or headers.  Check the mkmf.log file for more details.  You may  need configuration options.    Provided configuration options:      --with-opt-dir      --without-opt-dir      --with-opt-include      --without-opt-include=${opt-dir}/include      --with-opt-lib      --without-opt-lib=${opt-dir}/lib      --with-make-prog      --without-make-prog      --srcdir=.      --curdir      --ruby=/home/mink7/usr/local/2.3.0/bin/$(RUBY_BASE_NAME)      --with-pg      --without-pg      --enable-windows-cross      --disable-windows-cross      --with-pg-config      --without-pg-config      --with-pg_config      --without-pg_config      --with-pg-dir      --without-pg-dir      --with-pg-include      --without-pg-include=${pg-dir}/include      --with-pg-lib      --without-pg-lib=${pg-dir}/lib    To see why this extension failed to compile, please check the mkmf.log which can be found here:      /home/mink7/.gem/ruby/2.3.0/extensions/x86_64-linux/2.3.0-static/pg-0.18.4/mkmf.log    extconf failed, exit code 1    Gem files will remain installed in /home/mink7/.gem/ruby/2.3.0/gems/pg-0.18.4 for inspection.  Results logged to /home/mink7/.gem/ruby/2.3.0/extensions/x86_64-linux/2.3.0-static/pg-0.18.4/gem_make.out  

I have also run

sudo apt-get install gcc

and made sure the compiler is of the latest version.

Rails: how to retrieve the params for child objects in nested form

Posted: 08 Apr 2016 05:37 AM PDT

I have a wizard situation where I create a Parent object, and then build a form with 2 nested children.

The parameters that get submitted look like this:

Parameters: {"room"=>  {"parents_attributes"=>  {"0"=>{"name"=>"r2", "phone"=>"07443107986"},   "1"=>{"name"=>"", "phone"=>""}}},   "commit"=>"Go!", "id"=>"step03"}  

(the commit and id are from the wicked wizard step)

If the user refreshes the page, the id's for these children change and the parameters look like this:

Parameters: {"room"=>  {"parents_attributes"=>  {"1"=>{"name"=>"r2", "phone"=>"07443107986"},   "2"=>{"name"=>"", "phone"=>""}}},   "commit"=>"Go!", "id"=>"step03"}  

Since the id's are generated by the fields_for.

My controller code retrieves the data like this (the room is saved in the session on a previous step):

    @room = Room.find(session[:room_id])      @room.parents.build(room_params[:parents_attributes]['0'])      @room.parents.build(room_params[:parents_attributes]['1'])  

This obviously only works if the user does not refresh the page. Also, if validations fire the id's of the children change too.

What is a better way to retrieve these parent_attributes from the params hash?

EDIT

In the wizard step, the child objects are built like this:

when :step03    @room = Room.find(session[:room_id])    2.times{ @room.parents.build }  

Can i pass different currency in active-merchant with stripe in Rails 4 application?

Posted: 08 Apr 2016 06:28 AM PDT

I am developing Rails 4 application where user can subscribe one time pay with application.

For subscription, use Active Merchant with stripe where now user pay $50 right now and payment done successfully. Below code :

 ActiveMerchant::Billing::Base.mode = :test        transaction = ActiveMerchant::Billing::StripeGateway.new(:login => Rails.application.secrets.stripe_secret_key)        paymentInfo = ActiveMerchant::Billing::CreditCard.new(                  :number             => purchage_params[:card_holder_number],                  :month              => purchage_params[:expiry_month],                  :year               => purchage_params[:expiry_year],                  :verification_value => purchage_params[:cvv])          purchaseOptions = {:billing_address => {          :name     => purchage_params[:card_holder_name],          :currency => @country.currency,          :address1 => session[:address],          :city     => session[:city],          :state    => @region.name,          :zip      => session[:zip_postal]      }}        response = transaction.purchase((amount * 100).to_i, paymentInfo, purchaseOptions)  

Now my issue, I want to deduct payment as per user country wise. As per below country and payment.

 USA = $50 USD   South Africa = 355 ZAR   India = 520 INR   Australia = $50 AUD  

So how can i set currency and payment country wise. Any one have a idea in it?

Thanks

Activeadmin batch action caching query result

Posted: 08 Apr 2016 04:57 AM PDT

I am using a batch action in activeadmin to display a form and code is

batch_action 'Assign something', form: {        abc: Abc.order('name ASC').map{|s| [s.name, s.id]}.uniq    } do |ids, inputs|      ids.each do |id|        job = Job.find(id)        # does something here      end      redirect_to :back, notice: "Congrats!!"    end  

This code generates perfect form but in this form dropdown generated has cached values. That is if we modify name of any Abc record, its change is not reflected in the form even after refreshing the page.

Form has following options    <option value="6">Bla</option>  <option value="7">Alliance</option>  

After editing value Bla to Foo in DB our form still shows same old result. Though value in db has been changed.

After editing records. Though Bla should be changed to Foo now  <option value="6">Bla</option>  <option value="7">Alliance</option>  

Any idea where I am going wrong?

erroe with carrierwave for showing file?

Posted: 08 Apr 2016 06:21 AM PDT

I have installed gem and followed all the instructions.

rails g uploader File    rails g migration add_file_to_users file:string  

After that I uploaded the image as file and it succeeded.

Although it's uploaded, when I go to show it its not working.

My code in show.html.erb:

<%= image_tag @user.file_url if @user.file? %>  

I tried adding:

<%= @user.file.inspect %>  

but it's not showing me the url for image I uploaded.

Thank you.

imgkit get height of image

Posted: 08 Apr 2016 05:03 AM PDT

what I'd like to do is very simple. I have a code which uses a imgkit library to load some webpage image and then stores it. It looks like that:

kit = IMGKit.new(site, :quality => 5, :width => 1024)  img = kit.to_img(:png)  file = kit.to_file("#{Rails.root}/public/images/#{s2}.png")  

I need to know the image height after loading in order to stretch canvas element behind it. Is there a way I can get the height ? Or if not, how could I achieve this without knowing the image height before loading, javascript ?

Query concerning 3 tables and user input

Posted: 08 Apr 2016 04:44 AM PDT

I have three tables: Customer, Order and Versions. A customer has multiple orders and versions table consists of the latest version i.e, association of an agent with customer. I prompt the user to enter start and end date. For example if the user enters start_date: Jan 1,2016 and end_date:Mar 13,2016. But the latest version of the customer in version table is from 1st Feb,2016 . Hence instead of picking start date as Jan 1, I want to pick it up as 1st Feb.

I have written following scope: scope :ended_between, -> (start_time, end_time) { where('created_At >= ? AND created_at <= ?', start_time.to_i, end_time.to_i) }

This runs on entire table and I want to do it for all customers in one table. Can you please help me out to do the task in one query

Rails 4 : Brakeman is giving xss issue for js.erb files and not to .html.erb files

Posted: 08 Apr 2016 04:44 AM PDT

I am using brakeman security tool to find the security issues in my web application. Brakeman is showing me two xss attacks in the js.erb extension file.

I solved these xss issues by using sanitize method that rails provides to escape string.

But my question is in my other html.erb view files i am showing model attributes without sanitizing them. why brakeman is not giving xss attack issue for these files html.erb file and giving only to js.erb file. Does rails 4 automatically escape model attributes for html.erb file??

want to pass two variable for two different partial

Posted: 08 Apr 2016 05:35 AM PDT

I have show.html.erb file for user here i add partial file a details as _details.html.erb in detail page i have partial as _form.html.erb

Now i did code like this.Have partial file code in show.html.erb

user  @user_entry    <%= render :partial => "users/details" ,:locals => {:user => user } %>  

have partial file code in _detail.html.erb

<%= render :partial => "users/form" %>  

I have this two user & @user_entry i want @user_entry variable in form partial how can i ?

help me if anyone know

Thank you.

Regarding Rails Application Login

Posted: 08 Apr 2016 05:14 AM PDT

I am trying to deploy my rails application. I have a small requirement here.

I am not using Devise. I am providing user to login via his username and password. But now I also want to provide user to login via his email too.

How can I make this work. It should work for username and also for email.

My access controller login action is like this:

  def attempt_login      if params[:username].present? && params[:password].present?        p 'Fields Check'        found_user = User.where(:username => params[:username]).first        p "#{@found_user.inspect}"        if found_user          authorized_user = found_user.authenticate(params[:password])        end      end      p "#{authorized_user.inspect}"      if authorized_user        if authorized_user.email_confirmed          # mark user as logged in          session[:user_id] = authorized_user.id          session[:username] = authorized_user.username          redirect_to(:controller => 'users',:action => 'index')        else          flash[:error] = 'Please activate your account by following the          instructions in the account confirmation email you received to proceed'          redirect_to(:controller => 'home',:action => 'index')        end      else        p "Not a Registered User"        flash[:error] = "Invalid username/password combination."        redirect_to(:controller => 'home',:action => 'index')      end    end  

Thanks in advance :)

postgresql error in Cloud9 "fe_sendauth: no password supplied"

Posted: 08 Apr 2016 06:59 AM PDT

I'd like to setup postgresql for my rails app in Cloud9.

Although I followed the top voted answer of this post, the following error appeared when I tried to bundle exec rake db:create.

fe_sendauth: no password supplied  ...  Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "pool"=>5, "username"=>nil, "password"=>nil, "host"=>"0.0.0.0", "database"=>"app_development"}  fe_sendauth: no password supplied  ...  Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"unicode", "pool"=>5, "username"=>nil, "password"=>nil, "host"=>"0.0.0.0", "database"=>"app_test"}  

database.yml

default: &default    adapter: postgresql    encoding: unicode    pool: 5    username: <%= ENV['USERNAME'] %>    password: <%= ENV['PASSWORD'] %>    host:     <%= ENV['IP'] %>    development:    <<: *default    database: app_development    test:    <<: *default    database: app_test    production:    <<: *default    database: app_production  

Gemfile

gem 'pg', '~> 0.18.2'  

Although I found similar questions in stackoverflow, they doesn't work for me.

It would be appreciated if you could give me how to avoid this error.

Cloud 9 can't allow us to access to the pg_hba.conf file as this post mentioned.

EDIT!!!

host: localhost was added instead of host: <%= ENV['IP'] %> in "database.yml"

sudo vim /etc/postgresql/9.3/main/pg_hba.conf

# "local" is for Unix domain socket connections only  local   all             xxx                                     peer  

instead of

# "local" is for Unix domain socket connections only  local   all             username                                     peer  

pg_search gem ignore html links

Posted: 08 Apr 2016 04:28 AM PDT

My configurations for PgSearch

# config/initializers/pg_search.rb  PgSearch.multisearch_options = {    using: { tsearch: { prefix: true } }  }  

I can't find html links in records. When i have a record with text

<p> My text go here <a href="https://my_bt.s3.amazonaws.com/Signage.pdf">file</a> </p>   <p> other paragraph </p>  

when perform this code

query = 'my_bt.s3.amazonaws.com'  PgSearch.multisearch(query)# => []  

but when request not contain a link like query = '<p>My text go here' - record can be found

Why it happens?

Getting error in Activeadmin NoMethodError - undefined method `login'

Posted: 08 Apr 2016 05:07 AM PDT

I am using active admin for admin side.

I installed active-admin gem and executed rails g active_admin:install.

After that when I tried to open login page for admin. I am getting this error.

NoMethodError - undefined method `login' for #:

ActionDispatch::ParamsParser::ParseError for String Request Payload

Posted: 08 Apr 2016 06:40 AM PDT

I'm receiving a standard request from an API. It looks something like this :

enter image description here

It's content type and length is :

enter image description here

But when this hits my Rails server, Rails responds with

enter image description here

The reason I'm bringing this up, is because the same request seems to work on SCORM Cloud's server. If I upload the exact same content to them, and watch it in the debugger, I see it send out an application/json statement with the same Request payload, but with no unexpected token error.

Does a Rails application/json request have to be written a certain way that differs from other servers? Is there a proper way to rewrite this line in Rack Middleware to prevent this error?

Update

The javascript :

function _TCDriver_XHR_request (lrs, url, method, data, callback, ignore404, extraHeaders) {  _TCDriver_Log("_TCDriver_XHR_request: " + url);  var xhr,      finished = false,      xDomainRequest = false,      ieXDomain = false,      ieModeRequest,      title,      ticks = ['/', '-', '\\', '|'],      location = window.location,      urlParts,      urlPort,      result,      extended,      until,      fullUrl = lrs.endpoint + url  ;    urlParts = fullUrl.toLowerCase().match(/^(.+):\/\/([^:\/]*):?(\d+)?(\/.*)?$/);    // add extended LMS-specified values to the URL  if (lrs.extended !== undefined) {      extended = [];      for (var prop in lrs.extended) {          if(lrs.extended[prop] != null && lrs.extended[prop].length > 0){              extended.push(prop + "=" + encodeURIComponent(lrs.extended[prop]));          }      }      if (extended.length > 0) {          fullUrl += (fullUrl.indexOf("?") > -1 ? "&" : "?") + extended.join("&");      }  }    //Consolidate headers  var headers = {};  headers["Content-Type"] = "application/json";  headers["Authorization"] = lrs.auth;  if (extraHeaders !== null) {      for (var headerName in extraHeaders) {          headers[headerName] = extraHeaders[headerName];      }  }    //See if this really is a cross domain  xDomainRequest = (location.protocol.toLowerCase() !== urlParts[1] || location.hostname.toLowerCase() !== urlParts[2]);  if (! xDomainRequest) {      urlPort = (urlParts[3] === null ? ( urlParts[1] === 'http' ? '80' : '443') : urlParts[3]);      xDomainRequest = (urlPort === location.port);  }    //If it's not cross domain or we're not using IE, use the usual XmlHttpRequest  if (! xDomainRequest || typeof XDomainRequest === 'undefined') {      _TCDriver_Log("_TCDriver_XHR_request using XMLHttpRequest");      xhr = new XMLHttpRequest();      xhr.open(method, fullUrl, callback != null);      for (var headerName in headers) {          xhr.setRequestHeader(headerName, headers[headerName]);      }  }  //Otherwise, use IE's XDomainRequest object  else {      _TCDriver_Log("_TCDriver_XHR_request using XDomainRequest");      ieXDomain = true;      ieModeRequest = _TCDriver_GetIEModeRequest(method, fullUrl, headers, data);      xhr = new XDomainRequest ();      xhr.open(ieModeRequest.method, ieModeRequest.url);  }  

Twilio track call status using twilio.js

Posted: 08 Apr 2016 04:54 AM PDT

I have twilio.js setup in my rails application and works well, now what I need is after the call is disconnected I want to know the call status, if the call is not attended I have to call another number this is my disconnect function, how to check the call status using twilio.js?

Twilio.Device.disconnect(function(connection) {    // Disable the hangup button and enable the call buttons    hangUpButton.prop("disabled", true);    callCustomerButtons.prop("disabled", false);    callSupportButton.prop("disabled", false);    updateCallStatus("Ready");  });  

Select2 with ajax gets initialized several times with Rails turbolinks events

Posted: 08 Apr 2016 03:49 AM PDT

I am a developing a Ruby On Rails app using Rails 4.2.6. I am using Turbolinks alongside jquery.turbolinks (sorry I could'nt post the links to those elements as I am a newbie on the site). My problem is very simple but I just can't solve it. Here it is: I have a form fetched through AJAX

<div class="card-footer">    <a class="btn btn-sm btn-primary-outline" data-remote="true"  href="/profiles/Mke5kA/positions/new"><i class="fa fa-plus"></i> Nouvelle expérience professionnelle</a>    <div id="new_position_form"></div>  </div>  

The form contains Select2 elements that get their data through AJAX

= simple_form_for [profile, position], remote: true, html: {id: 'positionForm', class: 'm-b-1'} do |f|    = f.input :company_id, as: :select, input_html: {:'data-behaviour' => 'company-select2', :'data-kind' => 'company'}    = f.input :title    = f.input :summary    - location = f.object.build_location    = f.simple_fields_for :location do |l|      = render 'locations/fields', l: l, city: position.city    = render "profiles/shared/date_fields", f: f, model: position    = f.input :skill_list, as: :select, input_html: {multiple: true, :data => {:behaviour => 'acts-as-taggable', :'taggable-context' => 'skills'}}    %button.btn.btn-primary{:type => "submit"}= icon('check-square-o', 'Enregistrer')    = link_to icon('remove', 'Annuler'), 'javascript:void(0)',           data: {:'lgnk-behaviour' => "remove-form", :'lgnk-target' => "#positionForm" }, class: 'btn btn-secondary'  
  • The Select2 elements are "activated" currently upon Rails Trubolinks events "page:load page:update", but I have also tried "page:change"
  • When the form is fetched: the select2 elements are fine (activated correctly):

Initial form (after AJAX fetch

My problem appears when I try typing in the Select2 that are using AJAX to get the data: all the select2s are duplicated:

enter image description here

Here is how I get the Select2 initialized:

var loc_tag = function() {    $('[data-behaviour="acts-as-taggable"]').not('.select2-hidden-accessible').each (function (index, element) {      if ($(element).data('value')) {        var options = $(element).data('value').split(', ');        $.each(options, function(key, tag){          $(element).append($('<option selected></option>').val(tag).text(tag));        });      }        $(element).select2({        ajax: {          url: "/tags?context="+$(element).data('taggable-context'),          dataType: 'json',          headers: {           "Accept": "application/json"          },         delay: 250,         data: function (params) {           return {             q: params.term, // search term             page: params.page           };         },         processResults: function (data, page) {           return {             results: data           };        },        cache: true      },      escapeMarkup: function (markup) { return markup; }, // let our custom formatter work      minimumInputLength: 2,      tags: true,      language: "fr",      theme: "bootstrap",      width: "100%",      placeholder: 'Mots clés...'      });    });    };  $(document).on('page:load page:update', loc_tag);  

I want the Select2 elements to get initialized only once (when the form is fetched) and not upon AJAX responses on them getting their data. I have tried jQuery.not(".select2-hiden-accessible") on the elements unsing Select2 (select2-hidden-accessible being the class Select2 adds to an initialized Select2 element) but it does not work.

Many thanks for your kind help!

Rails query param in URL twice

Posted: 08 Apr 2016 04:26 AM PDT

I have a search form that searches a geocoded model called property. The geocode search works fine. However when I introduce more params to the search it returns incorrect results.

I have two boolean columns on the property model, smokers and pets. In my URL I notice that the same query param for pets is inserted twice:

http://localhost:3000/properties?utf8=%E2%9C%93&location=L17+6DD&distance=10&pets=false&pets=true&smokers=false&commit=Search

I'm using Rails 4.2.6, Ruby 2.3.0 and PostgreSQL

Search form:

<%= form_tag properties_path, method: :get do %>      <%= label :location, "Search properties near : " %>      <%= text_field_tag :location, params[:location] %>        <%= label :distance, "Distance : " %>      <%= text_field_tag :distance, params[:distance] %>        <%= label :pets, "Pets : " %>      <%=hidden_field_tag 'pets', false%>      <%=check_box_tag 'pets', true %>      <%= label :smokers, "Smokers : " %>      <%=hidden_field_tag 'smokers', false%>      <%=check_box_tag 'smokers', true %>        <%= submit_tag "Search" %>  <% end %>  

Properties controller action:

def index  if params[:location].present?    @properties = Property.near(params[:location], params[:distance] || 10)                      .where("pets = :pets", {pets: params[:pets]})                      .where("smokers = :smokers", {smokers: params[:smokers]})    else    @properties = Property.all  end  

end

Location model as polymorphic association

Posted: 08 Apr 2016 04:07 AM PDT

I hope I'm forming this question correctly. But I'm trying to create a location model that has a geocoded address and that address is able to be located on a map using gmap for rails.

My issue is associating my Location model with other application models. Currently I'm attempting to have a location field within my post form.

My application is as followed using the geocoder and gmaps for rails gems.

class Location < ActiveRecord::Base  belongs_to :locatable, polymorphic: true  belongs_to :post  geocoded_by :address  acts_as_gmappable    after_validation :geocode     validates :address, presence: true  validates :latitude, presence: true  validates :longitude, presence: true    def gmaps4rails_address    "#{address}"  end  validates :locatable, presence: true    end  

Post model

class Post < ActiveRecord::Base    has_one :location, as: :locatable , :dependent => :destroy    accepts_nested_attributes_for :locations,:reject_if =>:all_blank ,allow_destroy: true  end   

Controllers

Post Controller

def new    @post= current_user.posts.build  end  def create    @post = current_user.posts.new(post_params)    @post = Location.new    if @post.save      redirect_to root_path    else      render 'new'      flash[:error] = !"    end  end    def post_params    params.require(:post).permit(locations_attributes[:address,:latitude,:longitude, :locatable_id, :locatable_type, :gmaps])  end          

Locations Controller

class LocationsController < ApplicationController    def new    @location = Location.new  end    def create     @location = Location.new(params[:location])  end    def destroy    @location.destroy    respond_to do |format|    format.html { redirect_to locations_url, notice: 'Location was successfully destroyed.' }    format.json { head :no_content }  end  end    private    def location_params    params.require(:location).permit(:address, :latitude, :longitude, :locatable_id, :locatable_type, :gmaps)  end  end  

My code might be snippet out but my overall issue is happening within the controller I have everything going right. The location field within my post form is a nested form of the model location, the address field is geocoded and has a location search for the address input. My problem arises when submitting the post, I've tried several methods but I cannot get the location to save to post model. Any help would be amazingly helpful.

Rspec & ShouldaMatchers with class_name

Posted: 08 Apr 2016 03:35 AM PDT

I'm getting following error:

1) Admin should belong to hospital   Failure/Error: it {should belong_to(:hospital).with_foreign_key('medical_facility_id')  }     Expected Admin to have a belongs_to association called hospital ()  

with:

#admin_spec.rb    it {should belong_to(:hospital).with_foreign_key('medical_facility_id')  }  

Models are:

class Admin < ActiveRecord::Base    belongs_to :hospital  end    class Hospital < MedicalFacility  end  

In schema.rb:

create_table "admins", force: :cascade do |t|      t.integer  "user_id",             null: false      t.string   "role",                null: false      t.integer  "medical_facility_id"      t.datetime "created_at",          null: false      t.datetime "updated_at",          null: false  end  

How to correctly write test for this model? Maybe I should add `class_name:"MedicalFacility" to the Admin model?

Large number of threads under unicorn

Posted: 08 Apr 2016 03:28 AM PDT

I am in the process of debugging some Posgtres connection leaks in our application. Few days back we suddenly crossed 100 connections when we should not be - coz we just have 8 unicorn workers and a sidekiq process (25 threads).

I was looking at htop today and saw that a ton of threads were being spawned from my unicorn workers. Eg:

enter image description here Am I reading this correctly? This should not be happening right? If these are threads being spawned, any idea how to debug this?

Thanks! Btw, my other problem - (Postgres connections) Debugging unicorn postgres connection leak

No comments:

Post a Comment