Friday, May 6, 2016

Double render error with rails Json API | Fixed issues

Double render error with rails Json API | Fixed issues


Double render error with rails Json API

Posted: 06 May 2016 06:57 AM PDT

I have a controller action in my API that looks like this :

  def invite      unless current_user.id != @account_asso.admin_user_id        user_already_exists_or_email_blank?        set_new_user        ActiveRecord::Base.transaction do          set_offices_access          save_user_and_send_invitation_email        end      else        render_error("not_admin")      end    end  

the action is calling the methods set_office_access and save_user_and_send_invitation_email :

private        def set_offices_access      if params[:office_access].first == "all"        @offices = @account_asso.offices      else        @offices = Office.where(id: params[:office_access])      end    end      def save_user_and_send_invitation_email      if @user.save &&  @user.offices << @offices        if UserMailer.send_invitation(@user, params[:app_base_url]).deliver_now          @user.invitation_sent_at = Time.now          if @user.save            render_success("mail_sent")          else            render :json => { :errors => @user.errors }          end        else          render_error("mail_processing")        end      else        render :json => { :errors => @user.errors }      end    end     def render_error(error_type)      case error_type        when "not_admin"           render json: {error: "You are not allowed to create a user for this account"}        when "mail_exists"           render json: {error: "Please fill the email field and try again"}        when "empty_email"          render json: {error: "Please fill the email field and try again"}        when "mail_processing"           render json: { error: "We couldnt send an email to your invitee. Please try again" }        when "db"          render json: {error: "An error occured. Please try again"}        when "unauthorized"          render json: {error: "Unauthorized"}        else          render json: { errors: @user.errors.full_messages }, status: :unprocessable_entity      end    end      def render_success(success_type)      case success_type        when "mail_sent"          render json: { success: "An email was sent to your collaborator asking him to join your Quickbed team." }        when "password_changed"          render json: {success: "Your password was successfully changed"}        when "updated"          render json: {success: "Your infos were successfully updated"}      end    end  

However when I have a validation error for example when I try to save the user in save_user_and_send_invitation_email, I get :

AbstractController::DoubleRenderError - Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".

I tried adding and return after the renders but it did not work.

How can I fix this ?

Using first_or_create in Sidekiq Job

Posted: 06 May 2016 06:52 AM PDT

I have a Sidekiq Job with first_or_create.

 class JobWithFirstOrCreate      analysis = Analysis.where(standard_id: standard_id).first_or_create      analysis.save!   end  

But this causes uniqueness validation to fail due to duplicate analysis records being created. I understand this is because first_or_create is not atomic.

So what is the right way of doing this?
I want to run jobs concurrently in which I update if an analysis record is already present else insert.

Not able to call a controller action in Rspec

Posted: 06 May 2016 06:52 AM PDT

I have been trying to implement an RSpec for a Controller called "Estimate controller" to test whether my mailing functionality (sending estimate) working properly or not. But I'm not able to call the controller action from my RSpec. I need to set some values (to, subject, message, cc, current_user, attachments) in a hash and send that hash to Estimate controller.Here is what I tried..

estimates_controller_spec.rb

    describe "post 'send_estimate'" do            it "should send estimate " do                @estimate = Fabricate(:estimate, id:  Faker::Number.number(10), validity: "12/12/2014", total_value: 1222.00, user_id:@user.id, project_id: @project_id)  est_params = {            to: "rspec@rails.com",            subject: "Estimate",            message: "Check out the Estiamte details",            cc: "respec@rails.com",            current_user: @user,            attachments: ""          }             expect{        post :send_estimate, estimate: est_params        }.to change { ActionMailer::Base.deliveries.count }.by(1)          end       end  

estimates_controller.rb

def send_estimate       respond_to do |format|        if @estimate.send_email(params[:to], params[:subject], params[:message], params[:cc], current_user, params[:attachments])          @estimate.create_activity :send_estimate, owner: current_user, recipient: @estimate.project          format.html  { redirect_to lead_path(@estimate.project), notice: "Email sent Successfully"}                  format.json { head :no_content, status: :ok}        else          format.json { render json: @estimate.errors }          format.html { redirect_to contacts_path, notice: 'Something went wrong' }        end            end           end  

Capybara Rspec Rails get ID for path

Posted: 06 May 2016 07:02 AM PDT

Using capybara/rspec to test rails. Want to check current path is generated correctly with the id but cant access the created Contact id.

Example expectation: localhost:3000/contacts/27

Example recieved: localhost:3000/contacts/

Code base:

feature 'contacts' do      before do        visit '/'        click_link 'Sign up'        fill_in 'Email', with: 'test@test.com'        fill_in 'Password', with: '123456'        fill_in 'Password confirmation', with: '123456'        click_button 'Sign up'        click_link 'Add a contact'        fill_in 'Firstname', with: 'John'        fill_in 'Surname', with: 'Jones'        fill_in 'Email', with: 'test@test.com'        fill_in 'Phone', with: '223344'        attach_file('contact[image]', Rails.root + 'spec/mouse1.jpeg')        click_button 'Create Contact'    end    context 'view a contact' do      scenario 'click contact to view details' do        click_link('Mouse1')        expect(page).to have_content 'John Jones 223344 test@test.com'        expect(page).to have_xpath("//img[contains(@src, \/html/body/a[2]/img\)]")        expect(page).to have_current_path(contact_path("#{@contact.id}"))      end    end  

Surprised the interpolation hasn't worked and throws error undefined method 'id' for NilClass using the below. Clearly it cant access the id.

expect(page).to have_current_path(contact_path("#{@contact.id}"))  

Also tried swapping it out with @p = Contact.find_by_id(params[:id]) then passing in the @p in the interpolation. But throws error undefined local variable or method params

Any ideas/thoughts?

How to handle large JSON data when exploring an API?

Posted: 06 May 2016 06:46 AM PDT

Often I find myself in the situation where I start exploring a new API and get back large JSON objects. And everytime I struggle to find a way to display them properly indented, so that I can easily see the structure and identify the parts relevant to my task.

Right now I am exploring the Z-Wave API for Razberry (Home Automation). I get back a JSON holding all the devices connected to the Home Automation network. It looks like this:

enter image description here

And I don't understand why Rails breaks the lines in the way it can be seen here, and why it doesn't manage to indent the JSON data properly. The output on the screenshot is the result of this controller code:

request = Net::HTTP::Get.new(uri)  request.basic_auth 'admin', 'bla'    response = Net::HTTP.start(uri.hostname, uri.port) do |http|    http.request(request)  end    @devices = JSON.parse(response.body)  render json: @devices  

It would be interesting to see how more experienced programmers handle JSON at this stage, when exploring the datastructure. How can I display the JSON in this style?:

    {"1":      {"instances":          {"0":{              "commandClasses":                  {"32":                      {"name":"Basic",                       "data":                          {"invalidateTime":1462455293,                           "updateTime":1462365990,                           "type":"empty",                           "value":null,                           "supported":                              {"invalidateTime":1462455293,                               "updateTime":1462365990,                               "type":"bool",                               "value":true},                           "version":      

how to custom respond json in activeadmin gem rails

Posted: 06 May 2016 06:27 AM PDT

I have a model Product. when i get respond @product type json

url : admin/prodcuts/14.json  result => {"id":14,"name":"hello test"}  

but i want to show nested attributes in product same like:

{"id":14,"name":"hello test",     "nested_attributes" => {      "number1" => "value1",      "number2" => "value2"      }  }  

how to custom it?

How to log in to a remote rails application using devise, omniauth

Posted: 06 May 2016 06:27 AM PDT

I have two applications, AppA and AppB, they are both Rails applications.

I have created a single sign-on mechanism using Devise, Omniauth and Doorkeeper. This is where if you are logged into AppA, then you will be authorised to AppB, since AppB makes a oauth call to AppA to check this. AppA has devise and currently you have to login there.

What I would like to be able to do is to create an ajax login form in AppB, and this would pass my credentials to Devise in AppA and give me access to AppB, instead of redirecting to appA and back.

I seem to be able to do this OK if I disable CSRF checking in AppA, but I would like to be able to have an alternative where I either don't have to do this, or I can provide an alternative without any security holes.

So my main question is if anyone has any idea how to do this, or if they have done something similar and have suggestions? Many Thanks,

Eamon

Get the current url and send ti via email on rails

Posted: 06 May 2016 06:28 AM PDT

I am new to Ruby on Rails.

I am building a system that will enable users to create "ticket(s)" this means to report a problem about the applications that a company has built, basically, my system is an email management system where I will track the "tickets" by a ticket-id, when the user creates a ticket he/she will have to provide an email-address where he will be contacted back(via comment).

So after the ticket has been sent(created by non-logged in user), I will comment back on that ticket, and so I am trying to get the absolute current URL and send it on email when I click a button to submit the comment, so the user who receives the email can click the link and will be redirected to the "show" view of this ticket.

Besides this, how is it possible to make sure via a token that only the user who provided the email when he created the ticket, will have access to the link that has been sent on his email.

Let me summarise: so far, I have the class Tickets. Where non-logged in users can create tickets. I have the class Users(only for my staff members, so Devise takes place here). The staff members can read, assign, mark and comment back on tickets.

And so far I know that: request.original_url - will get the absolute current url.

And my routes:

resources :tickets do      resources :comments      member do        put :toggle_resolved      end    end  

Thank you in advance. Best. Ibrax

devise_token_auth for frontend and devise for backend - Why is it taking so long to sign in?

Posted: 06 May 2016 06:16 AM PDT

It seems like it is working correctly except, it will chug at the User Load step for about a minute before moving to the Spree::Order Load step. Can someone tell me the best way to find out why? I'm using postgres as my database.

User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."email" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["email", "devise@init.com"]]  Spree::Order Load (0.4ms)  SELECT "spree_orders".* FROM "spree_orders" WHERE "spree_orders"."email" = $1 AND "spree_orders"."guest_token" = $2 AND "spree_orders"."user_id" IS NULL  [["email", "devise@init.com"], ["guest_token", "Q_bFSuJM4PWb1aXRYWGqyA1462498805858"]]     (0.1ms)  BEGIN  SQL (0.3ms)  UPDATE "users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "users"."id" = $5  [["last_sign_in_at", "2016-05-05 18:42:22.571406"], ["current_sign_in_at", "2016-05-06 12:36:33.374732"], ["sign_in_count", 5], ["updated_at", "2016-05-06 12:36:33.376063"], ["id", 8]]     (3.6ms)  COMMIT  Spree::Role Load (0.1ms)  SELECT "spree_roles".* FROM "spree_roles" INNER JOIN "spree_role_users" ON "spree_roles"."id" = "spree_role_users"."role_id" WHERE "spree_role_users"."user_id" = $1  [["user_id", 8]]  Redirected to http://localhost:3000/parts/admin/orders  Completed 302 Found in 107746ms (ActiveRecord: 5.1ms)  

Rails 4: Separate model and controller functions with validations

Posted: 06 May 2016 06:12 AM PDT

I am trying to separate some logic from my controller but cannot get it working the way I'd like. I have a function in my controller that takes a CSV file and enters each row into my WeighIns table:

# Controller (WeighIn belongs_to User)    def bulk_upload_weigh_ins      import = WeighIn.import(params[:file])      redirect_to import_weigh_ins_path, notice: "Weigh Ins Imported Successfully!"  end  

Then I have the CSV parsing function in my model

# WeighIn model        def self.import(file)      CSV.foreach(file.path, headers: true) do |row|          hashed_row = row.to_hash          # VALIDATE HERE          WeighIn.create hashed_row      end  end  

but before creating the entry in the WeighIns table, I want to ensure there is a corresponding User for an attribute in the hash, i.e. User.find_by(scale_id: hashed_row["scale_id"]) != nil where scale_id is part of the row and a column on my User table.

How can I validate this and return a useful error that tells me there is "No User for scale_id: Foo"

Rails Spree 3.0.5 create promotion outside admin panel

Posted: 06 May 2016 06:09 AM PDT

I want to send email for user, who buy a product, with a unique coupon to the next order. I know how can i create promotion and promotion_rule, but I don't now how can I add promotion_action.

For example:

User buy a T-shirt in my store. Then he(she) paid for it, I need to generate a new coupon with fixed discount(e.g. 5$) and send email to the user with this coupon.

Firstly, I need to create a new promotion with some code and usage_limit = 1. Next thing what I need to do, is create new rule, that only registreted users can use this coupon. And the last I need to create a promotion action with fixed discount.

How can I do last step?

How do I Connect One Table To Multiple Tables?

Posted: 06 May 2016 06:05 AM PDT

We have many existing tables right now in our database. For easier understanding lets say we have tables with these names:

test_one, test_two, test_three, test_four, test_five, test_statuses  

Each of these belongs_to :user

What I want to do is create tracks for certain tests to belong to. So for instance, test_one, test_two, test_statuses belong to track_one and test_three, test_four, test_five, test_statuses belong to track_two. Each of these tracks belongs_to :user.

The thing that is tripping me up is how to tie all of these together. Each user should only have one of each track, and each track should have access to all data inside of the track.

The only thing I can think to do is something like:

test_one belongs_to track_one  test_two belongs_to track_one  test_statuses belongs_to track_one  test_statuses belongs_to track_two  test_three belongs_to track_two  test_four belongs_to track_two  test_five belongs_to track_two  

But this seems extremely sloppy and I'm not even sure if it will work.

If you need more information or don't understand, let me know and I can try to word it better or describe in more detail.

Paid membership Stripe Ruby

Posted: 06 May 2016 06:21 AM PDT

I've been dealing with some errors ive been getting and lately somehow i made it happend but there's a thing i need to add a metadata to my code but dont know where too and how I need your help.

Paid member is being registered but he's not being charge because its being registered without plan.

I guess this is what I need to add :metadata[plan_id]=2

    class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable    belongs_to :plan    has_one :profile    attr_accessor :stripe_card_token      def save_with_payment      if valid?        require "stripe"        Stripe.api_key = "********"          customer = Stripe::Customer.create(            :description => email,            :source => stripe_card_token # obtained with Stripe.js            )        self.stripe_customer_token = customer.id        save!      end    end  end                  /* global $*/  /* global Stripe*/  /* global Token*/  $(document).ready(function() {    Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));    // Watch for a form submission:    $("#form-submit-btn").click(function(event) {      event.preventDefault();      $('input[type=submit]').prop('disabled', true);      var error = false;      var ccNum = $('#card_number').val(),          cvcNum = $('#card_code').val(),          expMonth = $('#card_month').val(),          expYear = $('#card_year').val();        if (!error) {        // Get the Stripe token:        Stripe::Token.create({          number: ccNum,          cvc: cvcNum,          exp_month: expMonth,          exp_year: expYear,          }, stripeResponseHandler);      }      return false;    }); // form submission      function stripeResponseHandler(status, response) {      // Get a reference to the form:      var f = $("#new_user");        // Get the token from the response:      var token = response.id;        // Add the token to the form:      f.append('<input type="hidden" name="user[stripe_card_token]" value="' + token + '" />');        // Submit the form:      f.get(0).submit();     }  });  

Deploying Rails app with Apache, Passenger, Faye server, Private_pub

Posted: 06 May 2016 05:55 AM PDT

I'm trying to deploy a Rails app on a RHEL server (CentOS 6) using Apache and Passenger. The app has a chat feature that uses private_pub. Currently the app is running on port 80 and the Faye server (for private_pub) is running on 8080. The app seems to be sending information to the Faye server. However, it does not seem to be getting any information back.

If you navigate to 8080 directly, you get the correct Faye response. It looks like Faye is running correctly but something is up with the configuration, blocking the Rails app from processing a response. Any tips?

Failure/Error: ReferenceError: Can't find variable on upgrade of teaspoon-jasmine 2.3.4

Posted: 06 May 2016 05:40 AM PDT

Upgraded teaspoon-jasmine to 2.3.4 and jasmine to 2.4.0. All tests are failing it may be because of some configuration that i missed. Error it throws is :

Failure/Error: ReferenceError: Can't find variable $..

Any suggestions on how it can be fixed?

Other information required if radio button selected, using Rails and Jquery validate

Posted: 06 May 2016 05:33 AM PDT

I'm using the rails simple form gem and validating my form using the jquery validation plugin. I want to require "other information" when a radio button is selected as "yes" (or true). The rest of the validations I have are working fine but when I try to require text in an "other information", It's not being required. Here's my js

$(document).ready(function() {      var $validator = $("#new_nightclub").validate({            rules: {              "nightclub[form_writer_name]": {                required: true,                minlength: 3,                  maxlength: 40,              },              "nightclub[postal_address][postcode]": {                postcodeUK: true,              },              "nightclub[other_interests][line2]": {                  required:'#nightclub[other_interests][line1]:checked',                  minlength: 5,              },              "nightclub[confirmation]": {                required: true,              },            }          });  

And the part in question

<%= f.simple_fields_for :other_interests do |oi| %>             <%= oi.input :line1, as: :radio_buttons %>                  <p>If 'Yes', please provide full details in the box below.</p>             <%= oi.input :line2, as: :text %>             <% end %>         

I've based my code on the dependency-expression found here https://jqueryvalidation.org/required-method#dependency-expression. I'm just learning rails so appreciate any help thanks!

How to add multiple callbacks to rolify gem

Posted: 06 May 2016 05:43 AM PDT

According to rolify gem documentation. This gem adds the rolify method to your User class. You can also specify optional callbacks on the User class for when roles are added or removed:

class User < ActiveRecord::Base    rolify :before_add => :before_add_method      def before_add_method(role)      # do something before it gets added    end  end  

The rolify method accepts the following callback options:

before_add  after_add  before_remove  after_remove  

Mongoid callbacks are also supported and works the same way.

when i add multiple callbacks to rolify it only works for last one my code

class User < ActiveRecord::Base    rolify :before_add => :before_add_method    rolify :before_remove => :before_remove_method      private      def before_add_method(role)    #to do    end    def before_remove_method(role)    #to do    end  end  

only before_remove_method method called. Any suggestion how we can add multiple callbacks to rolify gem?

Conditional Route on sign_out using Devise with Rails

Posted: 06 May 2016 06:54 AM PDT

I am working on an app in which there is a model User with roles member and Admin.

As per requirement, I have to made two separate login pages for Admin and Member.

with http://localhost:3000/admin/admin_login

it goes to admin login page and with

http://localhost:3000/users/sign_in

it goes to member login page. Just after login I route them according to their roles to Admin panel or simple website for members.

But at time of logout both goes to http://localhost:3000

but I want admin to go to http://localhost:3000/admin/admin_login, while http://localhost:3000 is fine for member's logout.

Is there a way to see User's Role at time of Sign_out and route them accordingly.

How to save image from url to local ubuntu folder from rails console?

Posted: 06 May 2016 06:02 AM PDT

I need to write image parser from some website which will take images, some other info and save it to my local folder. So let's say we have image at this url : https://i.stack.imgur.com/MiqEv.jpg (this is someone's SO avatar)

So I want to to save it to local folder. Let's say to "~/test/image.png" I found this link

And I tried this in my terminal:

rails console    require 'open-uri'    open('~/test/image.jpg', 'wb') do    |file| file << open('https://i.stack.imgur.com/MiqEv.jpg').read  end  

As you can see my home/test folder is empty enter image description here

And I got this output from console #<File:~/test/image.jpg (closed)>enter image description here

What do I do?

Also I tried this:

require 'open-uri'  download = open('https://i.stack.imgur.com/MiqEv.jpg')  IO.copy_stream(download, '~/test/image.jpg')  

And got this output:

=> #https://i.stack.imgur.com/MiqEv.jpg>, @meta={"date"=>"Fri, 06 May 2016 11:58:05 GMT", "content-type"=>"image/jpeg", "content-length"=>"4276", "connection"=>"keep-alive", "set-cookie"=>"__cfduid=d7f982c0742bf40e58d626659c65a88841462535885; expires=Sat, 06-May-17 11:58:05 GMT; path=/; domain=.imgur.com; HttpOnly", "cache-control"=>"public, max-age=315360000", "etag"=>"\"b75caf18a116034fc3541978de7bac5b\"", "expires"=>"Mon, 04 May 2026 11:58:05 GMT", "last-modified"=>"Thu, 28 Mar 2013 15:05:35 GMT", "x-amz-version-id"=>"TP7cpPcf0jWeW2t1gUz66VXYlevddAYh", "cf-cache-status"=>"HIT", "vary"=>"Accept-Encoding", "server"=>"cloudflare-nginx", "cf-ray"=>"29ec4221fdbf267e-FRA"}, @metas={"date"=>["Fri, 06 May 2016 11:58:05 GMT"], "content-type"=>["image/jpeg"], "content-length"=>["4276"], "connection"=>["keep-alive"], "set-cookie"=>["__cfduid=d7f982c0742bf40e58d626659c65a88841462535885; expires=Sat, 06-May-17 11:58:05 GMT; path=/; domain=.imgur.com; HttpOnly"], "cache-control"=>["public, max-age=315360000"], "etag"=>["\"b75caf18a116034fc3541978de7bac5b\""], "expires"=>["Mon, 04 May 2026 11:58:05 GMT"], "last-modified"=>["Thu, 28 Mar 2013 15:05:35 GMT"], "x-amz-version-id"=>["TP7cpPcf0jWeW2t1gUz66VXYlevddAYh"], "cf-cache-status"=>["HIT"], "vary"=>["Accept-Encoding"], "server"=>["cloudflare-nginx"], "cf-ray"=>["29ec4221fdbf267e-FRA"]}, @status=["200", "OK"]> 2.3.0 :244 > IO.copy_stream(download, '~/test/image.jpg') => 4276 enter image description here

But my folder is still empty. What do I do??

Rails/JS Modal popup insert value in query

Posted: 06 May 2016 05:18 AM PDT

In a bootstrap Modal I want to give a value to Rails.

<a data-toggle="modal" data-id='<%=content.id %>'  class="open-FindMap" href="#FindMap">GoogleMaps</a>    <div id="map_canvas"></div>  

CoffeeScript:

$(document).on 'click', '.open-FindMap', ->   $('.modal-body #map_canvas').text $(this).data('id')  

That works. 12345 is shown.

Now I want to pass that value which replaces the div#map_canvas to Rails:

<% Model.find_by(content_id: ????)%>  

How to do that? Better ways to solve that? Thanks for help.

Ruby on Rails : Storing the pluck result

Posted: 06 May 2016 05:59 AM PDT

Im creating a library management system as part of a college assignment. Im currently stuck on obtaining the result of pluck.

The task Im trying to do here is to display a list of books that are currently in the table. Ive been primarily a PHP programmer so ruby on rails is a whole new world for me.

From doing external research I found out about object.pluck.

Book.pluck(:isbn,:title,:description,:author,:status)  

My knowledge of the above snippet is that Im pulling from all book objects there details. What I want to do is have a loop that will output each book followed by an edit button. In PHP this would be a form inside of a for loop. but with ruby I dont really know how to do it

In my head I want to store the result of the pluck in an array of books[]. Then use a loop to iterate through that loop and output details of the book stored at index i. But Im not sure how to store the result of pluck?

Include all ids in ActiveRecord query

Posted: 06 May 2016 05:25 AM PDT

I am developing a gaming platform and I have the following (simplified) models:

class Game < ActiveRecord:Base    has_many :game_players    has_many :players, through: :game_players  end    class Player < ActiveRecord:Base    has_many :game_players    has_many :games, through: :game_players  end    class GamePlayer < ActiveRecord:Base    belongs_to :game    belongs_to :player  end  

I need to perform an ActiveRecord query that looks for all games played by a certain group of users. For example, given the data:

+---------+-----------+  | game_id | player_id |  +---------+-----------+  |      10 |        39 |  |      10 |        41 |  |      10 |        42 |  |      12 |        41 |  |      13 |        39 |  |      13 |        41 |  +---------+-----------+  

I need to find a way to determine which games are played by the players with ids 39 and 41 which, in this case, would be the games with ids 10 and 13. The query I have found up to now is:

Game.joins(:players).where(players: {id: [39, 41]}).uniq  

However, this query is returning the games played by any of these players, instead of the games played by both of them.

Stripe do not save card detail in test server only

Posted: 06 May 2016 05:32 AM PDT

The card is being add in development server but while running test server and adding card detail for cucumber test it doesn't save the card and shows the following error.

ERROR Stripe::InvalidRequestError: Invalid token id: tok_18879VHs1bT44hDtvyLbWjOk

After commit callback for a particular ActiveRecord transaction

Posted: 06 May 2016 04:41 AM PDT

I have an ActiveRecord::Base transaction:

ActiveRecord::Base.transaction do    obj.update!(dummy: 'Hello World')  end  

and I want to trigger an after_commit only after this transaction commits its changes to the DB. Is there some way to go around this problem?

User saving his list before submit in ruby on rails

Posted: 06 May 2016 06:06 AM PDT

Hi i want to give two options for the user for his listing as, 1. Save 2. save and publish How could i do this in ruby on rails

How much traffic can a app on a Heroku free tier handle?

Posted: 06 May 2016 04:53 AM PDT

I want to know how many concurent number of users at a time can use app deploy on free tier of heroku?

Note : App server is by default

PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer

Posted: 06 May 2016 04:27 AM PDT

I am doing a "IN" query using prepared statements on rails. I am getting PG::InvalidTextRepresentation error.

code :

def mark_ineligible(match_ids)    ids = match_ids.join(", ")    result = epr("mark_matches_as_ineligible",                 "UPDATE matches SET is_eligibile=false WHERE id IN ( $1 )",                 [ids])  end    def epr(statementname, statement, params)    connection = ActiveRecord::Base.connection.raw_connection    begin      result = connection.exec_prepared(statementname, params)      return result    rescue PG::InvalidSqlStatementName => e      begin        connection.prepare(statementname, statement)      rescue PG::DuplicatePstatement => e        # ignore since the prepared statement already exists      end      result = connection.exec_prepared(statementname, params)      return result    end  end  

trying to invoke this using :

ids = [42, 43]  mark_matches_as_ineligible ids  PG::InvalidTextRepresentation: ERROR:  invalid input syntax for integer: "42, 43"        from (irb):24:in `exec_prepared'      from (irb):24:in `rescue in epr'      from (irb):15:in `epr'      from (irb):8:in `mark_ineligible'      from (irb):35  

Please help here. I want to know why I am getting this errors and how to fix it.

Thanks,

Sending object as a variable to Mandrill via Rails

Posted: 06 May 2016 06:20 AM PDT

I'm converting an email template from Rails to Mandrill, the content for which requires a fair amount of data, some of which is nested through several associations.

Therefore, I'd like to pass objects via Mandrill's global_merge_vars, such as the (simplified) following:

[{ 'name'=>'order', 'content'=> @order.to_json(include:                                                  { user: { only: :first_name } },                                                    methods: [:method1,                                                              :method2,                                                              :method3,                                                              :method4])  }]  

Which passes through to the mandrill template under the order variable similar to the following:

{"id":11,"number":"xxxx","item_total":"112.0"...   "user":{"first_name":"Steve"},"method1":"£0.00","method2":"£112.00",   "method3":"£112.00","method4":"£0.00"}  

The problem is, I can't access anything within order (using Handlebars), i.e. {{order.id}}, {{order['id']}} etc. wont work.

It's not an option to break out data into a large number of variables, as some elements are collections and their associations.

I believe the problem occurs as everything is stringified when the variables are compiled for Mandrill -- therefore breaking the JSON object -- with the following a snippet of what is sent across:

"global_merge_vars"=>[{"name"=>"order", "content"=>"{\"id\":11,  \"number\":\"xxxx\",\"item_total\":\"112.0\"...  

I can't seem to find any documentation / suggestions for dealing with this, so am wondering whether this it's possible to pass data of this nature, and, if so, how to correctly pass it to be able to access the objects in the Mandrill template. Any advice greatly appreciated!

Steve.

getting weird error in rails console

Posted: 06 May 2016 04:19 AM PDT

when i trying to perform any of rake command it will so me this error

shared_helpers.rb:78: warning: Insecure world writable dir /opt/android-sdk/tools in PATH, mode 040777  rake aborted!  Gem::LoadError: You have already activated rake 11.1.2, but your Gemfile requires rake 11.1.1. Prepending `bundle exec` to your command may solve this.  /home/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:34:in `block in setup'  /home/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:19:in `setup'  /home/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler.rb:92:in `setup'  /home/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/setup.rb:8:in `<top (required)>'  /home/examples/demo_app/config/boot.rb:3:in `<top (required)>'  /home/examples/demo_app/config/application.rb:1:in `<top (required)>'  /home/examples/demo_app/Rakefile:4:in `<top (required)>'  LoadError: cannot load such file -- bundler/setup  /home/examples/demo_app/config/boot.rb:3:in `<top (required)>'  /home/examples/demo_app/config/application.rb:1:in `<top (required)>'  /home/examples/demo_app/Rakefile:4:in `<top (required)>'  (See full trace by running task with --trace)  

help me solve this thank you.

Rails 4 unpermitted params error

Posted: 06 May 2016 06:23 AM PDT

I am receiving this error when a form submits:

Unpermitted parameters: postal_address_type_faos  

I can confirm that the params come in ok but it looks like the postal_address_type_faos is being removed.

This is the params whitelist:

    def paper_params      params.require(:paper).permit(:status, :signature_id, :name, :code,            :create_user_id, :update_user_id, :created_at, :updated_at,           phone_numbers_attributes: [:id, :phone_type_id,  :area_code, :number, :extension, :create_user_id, :update_user_id, :created_at, :updated_at, :_destroy],          postal_addresses_attributes: [:id, :postal_address_type_id, :country_id, :line_1,:line_2, :line_3, :city, :territory_id, :postal_zip_code,           :address_note, :latitude, :longitude,           :_destroy, :address_verification_status_id, :comment,   postal_address_type_faos_attributes: [:id, :postal_address_id, :postal_address_type_id, :fao, :create_user_id, :update_user_id, :created_at, :updated_at, :_destroy]])          end  

Models:

class Paper < ActiveRecord::Base    has_many :paper_postal_addresses    has_many :postal_addresses, through: :paper_postal_addresses    has_many :postal_address_type_faos, through: :postal_addresses      accepts_nested_attributes_for :postal_addresses    accepts_nested_attributes_for :postal_address_type_faos      has_many :phone_number_papers    has_many :phone_numbers, through: :phone_number_papers      accepts_nested_attributes_for :phone_numbers, allow_destroy: true    class PaperPostalAddress < ActiveRecord::Base    belongs_to :paper    belongs_to :postal_address    has_many :postal_address_type_faos, through: :postal_address    class PostalAddress < ActiveRecord::Base    has_many :postal_address_type_faos    has_many :postal_address_types, :through => :postal_address_type_faos      has_many :paper_postal_addresses    has_many :papers, through: :paper_postal_addresses      class PostalAddressTypeFao < ActiveRecord::Base    belongs_to :postal_address_type    belongs_to :postal_address    has_many :paper_postal_addresses, through: :postal_address    class PostalAddressType < ActiveRecord::Base    has_many :postal_address_type_faos    has_many :postal_addresses, through: :postal_address_type_faos  

View code from the address partial is something like this

<%= f.fields_for :postal_addresses do |address|%>          //some address stuff here            //then do address fao type stuff (index is populated but not shown here)  <%= f.fields_for :postal_address_type_faos, @paper.postal_addresses[address.index].postal_address_type_faos[index] do |fa| %>            <%= fa.check_box :postal_address_type_id, label: fa.object.postal_address_type.name %>             <%= fa.text_field :fao, label: fa.object.fao %>       <% end %>        <% end %>  

Params coming back as:

    {"utf8"=>"âœ"", "authenticity_token"=>"R8ukkukuykuk",       "paper"=>{"carrier_id"=>"",  "name"=>"",  "status"=>"Active","digital_id"=>"1","signature_id"=>"1", "phone_numbers_attributes"=>{"0"=>{"create_user_id"=>"1568", "phone_type_id"=>"2", "country_phone_code_id"=>"2", "area_code"=>"",   "number"=>"", "extension"=>""}}, "postal_addresses_attributes"=>{"0"=>{"country_id"=>"", "line_1"=>"", "line_2"=>"", "line_3"=>"", "city"=>"", "territory_id"=>"", "postal_zip_code"=>"", "subterritory"=>"", "comment"=>""},   "1"=>{"country_id"=>"", "line_1"=>"", "line_2"=>"", "line_3"=>"", "city"=>"", "territory_id"=>"", "postal_zip_code"=>"", "subterritory"=>"", "comment"=>""},   "2"=>{"country_id"=>"", "line_1"=>"", "line_2"=>"", "line_3"=>"", "city"=>"", "territory_id"=>"", "postal_zip_code"=>"", "subterritory"=>"", "comment"=>""}},   "postal_address_type_faos_attributes"=>{"0"=>{"postal_address_type_id"=>"1", "attention"=>""}, "1"=>{"postal_address_type_id"=>"0", "fao"=>""}, "2"=>{"postal_address_type_id"=>"0", "fao"=>""}, "3"=>{"postal_address_type_id"=>"0",   "fao"=>""}, "4"=>{"postal_address_type_id"=>"0", "fao"=>""}}}, "area_code_required"=>"", "formaction"=>"add_address", "action"=>"create",   "controller"=>"papers"}  

1 comment:

  1. awesome post presented by you..your writing style is fabulous and keep update with your blogs Ruby on Rails Online Course

    ReplyDelete