Tuesday, April 19, 2016

Xeditable Updates my DB but Doesn't Update my Page Asynchronously | Fixed issues

Xeditable Updates my DB but Doesn't Update my Page Asynchronously | Fixed issues


Xeditable Updates my DB but Doesn't Update my Page Asynchronously

Posted: 19 Apr 2016 07:31 AM PDT

Has anybody else had this problem?

I am using XEditable in my Rails app, and it's working almost perfectly. The database gets updated with the new information, but I have to hit refresh to see the changes. The beauty of this feature for me was the ansynchronisity! If anyone can help me out, I would really appreciate it.

      .list-group-item{ href: user_path(user), 'data-push' => true }      .row        .col-sm-4          %label Mobile Phone          %h5.list-group-item-heading                          = editable user, :mobile_phone, value: number_to_phone(user.mobile_phone, area_code: true).gsub(/^\+\d/, '')          .col-sm-8          %label Email          %h5.list-group-item-heading            = editable user, :email, type: 'text', pk: 1          :javascript           $(function() {             $.fn.editable.defaults.mode = 'popup';             $('.editable').editable({             });           });  

rspec test fails due to Paperclip::Storage::Ftp::NoServerAvailable on model delete

Posted: 19 Apr 2016 07:27 AM PDT

Today I'm having some troubles to mock an FTP connection in order to test my models. I'm using this gem to store Paperclip attachment via FTP

The gem works perfectly and let me manage my archive via ftp easily. But, in my rspec controller test I get Paperclip::Storage::Ftp::NoServerAvailable when I testing the delete method.

I unsuccessfully tried to mock my FTP connection in this way:

let(:server) { Paperclip::Storage::Ftp::Server.new }  let(:connection) { double("connection") }  before do      server.stub(:connection).and_return(connection)  end  

but it doesn't work.

The test is this

myobject = FactoryGirl.create(:myobject)  expect {      delete :destroy, {id: myobject.to_param}  }.to change(MyObjectClass, :count).by(-1)  

Which is the right way to write this test? I want to check if my action deletes my object no matter its attachments. And I'm sure the right way is avoid real connections.

What am I doing wrong? Thank you

How can I use Cancan to grant users privileges with exception?

Posted: 19 Apr 2016 07:34 AM PDT

In my app I have a model called Profile, which contains profile information for people. I also have a User model, and some users manage content on the site, and their privileges are managed with the Cancan gem. Each user has one profile, but there are many profiles not associated with users. Suppose I have two classes of users, a large amount of "editors" who can manage content, and a few "admins" who can do anything. I want to make it so editors can manage (create, edit, and delete) profiles unless that profile belongs to another user. How can I do this with Cancan?

I know how to limit a user's ability, such as

can :manage, Profile, :user_id => user.id  

but I want something like a logical condition, like "can manage profile, unless that profile is associated with a user and that user is not the current user".

How Seed Data Relationships in Rails?

Posted: 19 Apr 2016 07:16 AM PDT

I would like to put more than one subcategory per category or category per subcaregory and maybe a third category related on a seed.

for exemple: () = have

category >>>> item 1 item 2 item 3   subcategory >>>> item 2(subitem 1 subitem 2 subitem 3)  thirdcategory >>>> subitem 3(thirditem 1 thirditem 2)  

Someone have a idea the way to acomplish this with seeds?

the relationships is:

category has_many subcategories

subcategories has_many thirdcategories

Installing Fedena Online

Posted: 19 Apr 2016 07:02 AM PDT

I have been trying to host fedena for a little time now. I know how to configure it offline as in localhost but I want to host it and use it. Any suggestions on how I do that?

Ruby logger to append mode

Posted: 19 Apr 2016 06:58 AM PDT

My question is divided in 2 sections

Firstly, There are multiple ways to create a loggers (I using ActiveSupport::Logger) which inherit from Logger.

# Approach 1  logger = ActiveSupport::Logger.new('test.log')   logger.info "Test1" # => I see the auto flushing happens in this    # Approach 2  logger = ActiveSupport::Logger.new(File.new('test.log','a'))  logger.info "Test2" ## No auto flushing unless done logger.close  

So, I don't see a point with approach 2 no auto flushing happen in them.

Why does the auto flushing does not happen in approach 2?

Secondly,

If I happen to delete my log file none of above approach(mention above) ever create a new log file again and also not log the log message.

What should I do in the situation like this? How does Rails does this? Any clue?

Updating a sortable bootstrap table correctly

Posted: 19 Apr 2016 07:05 AM PDT

Can someone point me in the right direction of how to update this food_rank table correctly?

JSFiddle

Using Sortable Bootstrap Tables.

I am making a survey in which the user picks foods from categories and then ranks the foods. Then I need to be able to use the top 3 foods for the rest of the survey.

Currently it creates new food_ranks after the foods are picked and loads this page (post). Then each time a row in the table is moved, the database should update with the current order.

As it currently is I am getting: ArgumentError - wrong number of arguments (given 0, expected 1): Which I believe is because Update needs params in the url(?), I am not sure. How can I get this to update correctly? Am I over complicating things here?

Relevent Code

Routes:

  resources :food_ranks, except: [:index, :create, :update] do      post :update_row_order, on: :collection    end      post  "food_ranks" => "food_ranks#create", as: :create_food_rank    patch "food_ranks" => "food_ranks#update", as: :duplicate_error    get   "food_ranks" => "food_ranks#food_ranking", as: :food_ranks  

Controller: (I tried to make it similar to the example in Sortable Bootstrap Tables but it doesn't work for my situation)

class FoodRanksController < ApplicationController    before_filter :authenticate_user!      def create      @survey = current_user.survey      @food = @survey.foods      @food.each_with_index do |food, i|        @food_rank = FoodRank.new        @food_rank.user_id = current_user        @food_rank.food_id = food.id        @food_rank.row_order = i        if @food_rank.save!        else          flash.alert = "Your error message"        end        redirect_to food_ranks_path      end    end      def food_ranking      @survey = current_user.survey      @food = @survey.foods    end      def update_row order      @food_rank = FoodRank.find(food_rank_params[:food_id])      @food_rank.row_order_position = food_rank_params[:row_order_position]      @food_rank.save    end      def update order      @food_rank = FoodRank.find(food_rank_params[:food_id])      @food_rank.row_order_position = food_rank_params[:row_order_position]      @food_rank.save    end    private    def set_food_rank      @food = @survey.find(params[:id])    end      def food_rank_params      params.require(:food_rank).permit(:rank, :user_id, :food_id, :row_order_position)    end      # def set_foods_params    #   params.require(:survey).permit(:user_id, :food_id, :food_ids => [])    # end  end  

View:

<% @food.each_with_index do |food, i| %>  <div class="" style="position: absolute; top: <%= (37 * i) + 256 %>px; clear: left; display: block;              float: left; font-size: 1.35em; padding-top: 6px; height: 37px; width: 55px; text-align: center">  <%= i + 1 %>    </div>  <% end %>    <div class="panel panel-default" style="max-width: 470px; min-width: 420px">    <table class="table table-bordered table-striped" id="sortable">      <col style="width: 10%">      <thead>        <tr>          <th>            Rank          </th>          <th>            Food          </th>        </tr>      </thead>      <tbody>        <% @food.shuffle.each_with_index do |food, i| %>          <tr data-item-id=<%= "#{food.id}" %> class="item">            <td style="font-size: 1.2em; text-align: center">              <% i + 1 %>            </td>            <td style="cursor: move">            <div ><%= @food.find(food).name %></div>            </td>          </tr>        <% end %>      </tbody>    </table>  </div>      <%= button_to "Next", vas_questions_path(1), class: "col-md-offset-8 btn btn-primary btn-surv", method: :get %>  

How connect a Ruby on Rails written website with android app with same data base hosted on Heroku which uses Postgresql

Posted: 19 Apr 2016 06:41 AM PDT

hello I am Kashif I made a website with ruby on rails and now I wanted to make an android app and I want to use a single database for both website and app, I hosted the website on Heroku and Heroku uses the Postgresql, so how could I connect them Please help me

Sort grid in webpage with angularjs and rails

Posted: 19 Apr 2016 06:51 AM PDT

I want sort my web page with elements that differ in length. My intention are to eliminate white spaces.

The code that sorts the elements is:

<div class="col-5 search" ng-repeat="service in services">    <a class="service-card"  href="{{ service.url }}">      <h3 ng-bind-html="service.name | limitTo:30">{{service.name}}</h3>      <p ng-bind-html="service.description | limitTo:150 ">        <p>{{service.description.length >=   150 	? "..." : " "}}</p>        <p class="btn">ver mais</p>      </p>      <span ng-repeat="category in service.categories">{{ category.name }}.</span>    </a>  </div>

Rails: How to display error message without model name, association name

Posted: 19 Apr 2016 07:18 AM PDT

I'd like to display error message without model name, association name.

For example, the following error was displayed,

Rooms events base To time must be after from tim  

But I'd like to display only To time must be after from time.

The validate in my model is as followings;

validate do |e|    if e.start_at.present? && e.end_at.present? and e.start_at > e.end_at      errors[:base] << "To time must be after from time"    end  end  

It would be appreciated if you could give me how to display only To time must be after from time.

application.html.erb

    <% flash.each do |message_type, message| %>        <%= content_tag(:div, message, class: "alert alert-#{message_type}") %>      <% end %>  

Nested forms with cocoon: permission issue

Posted: 19 Apr 2016 06:40 AM PDT

I have a nested simple_form, and I use the gem cocoon. I have a challenge model, which has this in challenge.rb: accepts_nested_attributes_for :prizes And a challenge has_many prizes. When submitting the form, I get the error:

Unpermitted params: prizes  

Even if I authorized it in my strong params. I have used cocoon previously and managed to make it work, I can't find the issue here and I'm pulling my hair off.

In my challenges_controller.rb:

def create      @challenge = Challenge.create(challenge_params)      @challenge.user = current_user      authorize @challenge         if params["challenge"]["prizes_attributes"]        for k,v in params["challenge"]["prizes_attributes"]          @prize = Prize.create          @prize.challenge = @challenge          @prize.title = v.values[0].values[0]          @prize.save        end      end        if @challenge.save        redirect_to challenge_path(@challenge)      else        render :new      end    end    def challenge_params      params.require(:challenge).permit(:title,                                        :banner,                                        :user,                                        :start_date,                                        :end_date,                                        :tagline,                                        :slug,                                        :rules,                                        :category_id,                                        :organization,                                        prizes_attributes: [:id, :title])    end  

Also, in my form to create a challenge:

<%= simple_form_for @challenge do |f| %>          <%= f.error_notification %>          <div class="form-inputs">            <%= f.input :title, :label => "Titre" %>            <%= f.input :banner, :label => "Bannière", as: :attachinary %>            <%= f.input :tagline, :label => "Tagline" %>            <%= f.input :organization, :collection => @organizations,:label => "Organization", :include_blank => true%>            <%= f.input :rules, :label => "Lien vers le règlement" %>            <%= f.input :start_date, as: :string, input_html: {type: :date}, :label => "Date de début" %>            <%= f.input :end_date, as: :string, input_html: {type: :date}, :label => "Date de fin" %>            <%= f.input :category_id, :collection => @ancestors,:label => "Catégorie", :include_blank => true%>             <%= f.simple_fields_for :prizes do |p| %>                <%= render 'prize_fields', f: p %>              <% end %>              <%= link_to_add_association 'Ajouter un prix', f, :prizes %>          </div>          <div class="form-actions text-center">            <%= f.button :submit, "Soumettre", :class => "btn btn-primary" %>          </div>        <% end %>  

And in my prizes_fields partial:

<li>    <div class='row'>      <%= f.fields_for :prizes do |p| %>      <div class='col-xs-12 col-md-6'>        <div class="materiel-wrapper">          <%= p.text_field :title, class:"form-control", placeholder:"Titre" %>        </div>      </div>      <% end %>    </div>  </li>  

Does anybody see where I made a mistake ?

Thanks for your time and help

Rails + Griddler + Sidekiq as processor

Posted: 19 Apr 2016 06:04 AM PDT

Is that possible to use Sidekiq to perform as Griddler Processor ? Currently Griddler return a Griddler Object that I can't send to Sidekiq, and I need it to upload attachments to S3 Bucket.

Do you have any way to use Griddler with Sidekiq ?

Thanks

Active admin polymorphic association data auto select

Posted: 19 Apr 2016 06:58 AM PDT

I have two models in my rails application called service and image, the table relation is polymorphic: service has_many :images, :as => :imageable.

Provider model also has the same relation with image table.

How can I fetch the services and provider data for a select drap down on the image form?

Two similar apps share a DB needs to add migration on one app based on requirement and should run from other app

Posted: 19 Apr 2016 07:29 AM PDT

I have two similar rails app and use a common DB and based on the requirement we have to add migration on both app. Now I What I want

 -  Add a migration on app1   -  run rake db:migrate one app2  

It must run migration present on app1 and vice versa is it possible?

In simple any migration added on any app should be update DB when run rake db:migrate on other app.

I think we can do by rails engine but not sure how, any suggestion?

Calling Rails::VERSIOIN::MAJOR in controller call Haml::Rails erroneously

Posted: 19 Apr 2016 06:00 AM PDT

I am developing a rails application, version 4.2.6, with haml-rails, and I'm using the gem rails_email_preview, version 1.0.3, to preview emails before sending. This gem has a controller that uses Rails :: VERSION :: MAJOR to verify the rails' version.

When Rails :: VERSION :: MAJOR is called I get an error saying Haml :: Rails :: VERSION is undefined. I found that the above call is using Haml :: Rails module and not Rails :: VERSION module erroneously. To test I put on my application_controller the same call and got the same error. However, when I move the call to the application_helper it works without problem.

To continue the development I copied the controller to my application and used a helper method to call Rails :: VERSION :: MAJOR.

This works, but I think it is not ideal. I would like some suggestions to solve this problem without having to copy the controller to my application.

Thanks in advance,

Fernando

group by in view or controller

Posted: 19 Apr 2016 06:21 AM PDT

i am trying to loop through a list of products which a supplier sells via its different variants. i can get the list of products to display, but i wish to group these by the product id as to only display it once.

in my controller i have

@supplier = Supplier.joins(products: :variants).find(params[:id])  

in my view i have

- @supplier.variants.group_by(&:product_id).each do |product_id, item|      = render :partial => 'product', :locals => {:item => item }  

and my partial

= link_to shopping_supplier_path(item) do    %li.mdl-list__item.mdl-list__item--three-line      %span.mdl-list__item-primary-content        %span= item.product.name        %span.mdl-list__item-text-body          = item.product.description.downcase      %span.mdl-list__item-secondary-content        %i.material-icons          chevron_right      %hr  

which when the sql executes returns the following query

    Started GET "/shopping/suppliers/latte-cartelle-drive-thru-coffee-241---245-princes-hwy--ha-1" for 127.0.0.1 at 2016-04-19 23:22:08 +1000  Processing by Shopping::SuppliersController#show as HTML    Parameters: {"id"=>"latte-cartelle-drive-thru-coffee-241---245-princes-hwy--ha-1"}    User Load (0.6ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]    Supplier Load (32.7ms)  SELECT  "suppliers".* FROM "suppliers" WHERE "suppliers"."permalink" = $1  ORDER BY "suppliers"."id" ASC LIMIT 1  [["permalink", "latte-cartelle-drive-thru-coffee-241---245-princes-hwy--ha-1"]]    Supplier Load (41.9ms)  SELECT  "suppliers".* FROM "suppliers" INNER JOIN "variant_suppliers" ON "variant_suppliers"."supplier_id" = "suppliers"."id" INNER JOIN "variants" ON "variants"."id" = "variant_suppliers"."variant_id" INNER JOIN "products" ON "products"."id" = "variants"."product_id" INNER JOIN "variants" "variants_products" ON "variants_products"."product_id" = "products"."id" WHERE "suppliers"."permalink" = $1  ORDER BY "suppliers"."id" ASC LIMIT 1  [["permalink", "latte-cartelle-drive-thru-coffee-241---245-princes-hwy--ha-1"]]    Variant Load (0.9ms)  SELECT "variants".* FROM "variants" INNER JOIN "variant_suppliers" ON "variants"."id" = "variant_suppliers"."variant_id" WHERE "variant_suppliers"."supplier_id" = $1  [["supplier_id", 1]]    Rendered shopping/suppliers/_product.html.haml (53.5ms)  

error

NoMethodError at /shopping/suppliers/latte-cartelle-drive-thru-coffee-241---245-princes-hwy--ha-1  undefined method `name' for #<Array:0x007faa5302d5a0>  

rails passing a local variable to a partial got some errors

Posted: 19 Apr 2016 06:17 AM PDT

I'am trying to pass a local variable to a partial, but I got this error:

undefined local variable or method `blubb' for #<#<Class:0x00000007cb8c00>:0x00000007c79f78>  

My code looks like this:

 <% rate = Rating.where(["comment_id = ? and movie_id = ?", comment.id, @movie.id]) %>      <% @ratingvalue = rate[0][:ratingvalue] %>     <div class="col-md-3 text-right"><%= render :partial => "shared/starRating", :locals => {blubb: @ratingvalue} %> </div>  

When I inspect @ratingvalue there is my integer value inside.

Then in the partial I try to do this:

<%= blubb %>  

but then I got the error.

also tried this:

<%= :blubb %>  

but then only blubb is printed ...

What is going wrong?

Thanks for your help.

Filter products by categories using Rails & AJAX

Posted: 19 Apr 2016 06:15 AM PDT


I need to create a page that will display products by chosen filters. For simplicity I will use product categories as filters.

The page should have 2 areas:

  1. Where products are displayed.
  2. Where categories are displayed and a 'Clear All' button.

Scenario:

User visits the index page, all products are displayed. User clicks the 'Home category' and gets all the products that belong to this category. Then he clicks on the 'Shoes category' and now he sees all the products that belong to both categories ('Home category' or 'Shoes category'). User clicks on the 'Clear All' button (in order to reset the chosen categories), now all the products from all the categories are displayed.

My Code:

My models Product, Category, and join table causes_products.

Category

class Category < ActiveRecord::Base has_and_belongs_to_many :products end

Products

class Product < ActiveRecord::Base has_and_belongs_to_many :categories end

Products Controller:

class ProductsController < ApplicationController    def index      @products = Product.all      @categories = Category.all    end    def from_category      @products = Product.joins(:categories).where(categories: { id: params[:cat_id] })      respond_to do |format|        format.js      end    end  end  


products/index.html.erb:

<div class="grid">    <%= render 'sidebar_menu' %>    <%= render partial: 'product_grid', locals: { products: @products} %>  </div>  


products/_sidebar_menu.html.erb:

<% @categories.each do | cat | %>  <%= link_to cat.name, fetch_products_path(:cat_id => cat.id), :remote => true %>  <% end %>  


routes.rb

get "/fetch_products" => 'products#from_category', as: 'fetch_products'  


products/_products_grid.html.erb:

<div id="products_grid">    <%= render partial: 'products_list', locals: { products: products } %>  </div>  


products/_products_list.html.erb:

<% products.each do |product| %>      <div class="product_box">        product.name      </div>  <% end %>  


products/from_category.js.erb:

$("#products_grid").html("<%= escape_javascript(render partial: 'products_list', locals: { products: @selected } ) %>");  


The code works great only for one chosen category, but I would like it to be able to filter two or more categories as well. What changes do I need to make?

Thanks.


Thank you @max and @Jeffrey M Castro for helping me with my previous question.

Thanks to sebastialonso for his article "How to partials & AJAX, dead easy".

How can I customize the data: :confirm popup to prompt for an input, that will be appended to the request params?

Posted: 19 Apr 2016 06:36 AM PDT

Many places in my application, submitting forms and visiting post-links requires the user to specify some reasoning as to why they decided to do so (the comments/reasoning are used to track who did what changes internally).

Now for this reason, I would like to be able to change the behaviour of data: {confirm: "Are you sure you want to submit this form?"} to prompt for an input instead of just answering yes/cancel. I would like the box to appear with a an input field, which content will then be appended to the requests params, so I can store it from the controller.

How can I do this?

Rails RSpec random db

Posted: 19 Apr 2016 05:50 AM PDT

I am trying to figure out RSpec and have some problems. When I run my basic test:

require 'rails_helper'    describe Post do      before do      @post = Post.create!(title: 'foobar1', content: 'foobar'*5)    end      it 'orders by creation date' do      @new_post = Post.create!(title: 'foobar1', content: 'foobar'*5)      Post.order('created_at desc').all.to_a.should == ([@new_post, @post])    end  end  

It looks like I have some more mysterious posts in the db: Failures:

  1) Post orders by creation date       Failure/Error: Post.order('created_at desc').all.to_a.should == ([@new_post, @post])           expected: [#<Post id: 980190990, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">, #<Post id: 980190989, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">]              got: [#<Post id: 980190990, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">, #<Post id: 980190989, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">, #<Post id: 980190962, title: nil, content: nil, created_at: "2016-04-19 11:59:56", updated_at: "2016-04-19 11:59:56">, #<Post id: 298486374, title: nil, content: nil, created_at: "2016-04-19 11:59:56", updated_at: "2016-04-19 11:59:56">] (using ==)         Diff:         @@ -1,3 +1,5 @@          [#<Post id: 980190990, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">,         - #<Post id: 980190989, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">]         + #<Post id: 980190989, title: "foobar1", content: "foobarfoobarfoobarfoobarfoobar", created_at: "2016-04-19 12:38:50", updated_at: "2016-04-19 12:38:50">,         + #<Post id: 980190962, title: nil, content: nil, created_at: "2016-04-19 11:59:56", updated_at: "2016-04-19 11:59:56">,         + #<Post id: 298486374, title: nil, content: nil, created_at: "2016-04-19 11:59:56", updated_at: "2016-04-19 11:59:56">]  

Do You know what is the cause of this problem?

ROR email error end of file

Posted: 19 Apr 2016 07:02 AM PDT

I want to send an email to someone and set the SMTP, but it is not working...

EOFError in UsersnewController#create

code   controller  UserMailer.activation(user).deliver    class UserMailer < ActionMailer::Base      def activation(user)      @user = user       mail(to: user.email, subject: 'Welcome to The Compelling Image')    end    end  

activation.erb

hi

Completed 500 Internal Server Error in 10298ms    EOFError (end of file reached):          Rendered /home/digi-t6/.rvm/gems/ruby-2.3.0/gems/actionpack-4.1.5/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.9ms)    Rendered /home/digi-t6/.rvm/gems/ruby-2.3.0/gems/actionpack-4.1.5/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.5ms)    Rendered /home/digi-t6/.rvm/gems/ruby-2.3.0/gems/actionpack-4.1.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.5ms)    Rendered /home/digi-t6/.rvm/gems/ruby-2.3.0/gems/actionpack-4.1.5/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (22.7ms)  

What are callbacks doing in omniauth-facebook integration?

Posted: 19 Apr 2016 06:02 AM PDT

Documentation on omniauth-facebook mentions callbacks a lot, but I don't see callbacks inside the documentation, and I didn't need to write any callbacks (in the Javascript sense I'm used to) to make the authentication work.

Documentation: https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

For example:

By clicking on the above link, the user will be redirected to Facebook. (If this link doesn't exist, try restarting the server.) After inserting their credentials, they will be redirected back to your application's callback method.

devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }  

Callbacks Controller

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController    def facebook      @user = User.from_omniauth(request.env["omniauth.auth"])        if @user.persisted?        sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated        set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?      else        session["devise.facebook_data"] = request.env["omniauth.auth"]        redirect_to new_user_registration_url      end    end      def failure      redirect_to root_path    end  end  

I don't see any explicitly written callbacks here so I assume there is something going on behind the scenes.

But I'm kind of confused - what are the callbacks actually doing and what part of this code is a callback?

Apologies in advance if this is a super newbie question.

Rails ActiveRecord connection session

Posted: 19 Apr 2016 06:19 AM PDT

I have the following piece of code in Rails 3.2 + mySQL application:

ActiveRecord::Base.connection.execute("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED")  ActiveRecord::Base.transaction do                @book = ActiveRecord::Base.connection.execute("select * from books limit 1")  end  

As far as I understand the first statement will result in the next ONE transaction within same session to be in "READ UNCOMMITTED" isolation and then isolation will return to default.

My questions are: Can I be sure that the transaction block will always be executed in the same session? Also, can I be sure that no other transaction will take place in the same session between the first and the second statement?

I tried to Google for this topic, but as I am new to Rails I couldn't find any explanation that would make this clear to me. Any help would be appreciated!

Thank you!

Remove key from hash

Posted: 19 Apr 2016 05:54 AM PDT

I have to remove all keys which are representing empty string for example

inventory = {"4"=>"", "1"=>"51059441", "3"=>""}  

And The result should be

inventory = {"1"=>"51059441"}

Duplicating an entry on a relationship in Rails 4

Posted: 19 Apr 2016 05:45 AM PDT

I have the model Order with 2 association to Address.

class Order < ActiveRecord::Base        belongs_to :billing, class_name: 'Address', foreign_key: 'billing_address_id', autosave: true      belongs_to :shipping, class_name: 'Address', foreign_key: 'shipping_address_id', autosave: true  

Usually, if both addresses are the same, you would have both associations pointing to the same record, but let's say for a moment, that I wanted to make 2 entries on the table Address. How would I do that?

I tried it this way, but it does not seem to work...

@order.build_shipping shipping_params  @order.shipping.do_this()  @order.shipping.do_that()    @order.billing = @order.shipping.dup  @order.save  

How could I achieve this?

Recommended way to find a record in rails

Posted: 19 Apr 2016 05:31 AM PDT

I can see that the find method is now deprecated in rails. So what is the recommended way now?

Room.find(params[:id]  

Even though Room.find_by_id(params[:id]) works just want to know the recommended way

Google Places API does not return images for a place

Posted: 19 Apr 2016 05:19 AM PDT

I use Google Places API to retrieve information about some places. It works good, but in some situations [I can't find a pattern] the API does not return images for required place [identified by google place_id]. But if I search for same place in Google Maps, it has lots of photos. An example of this kind of place is "Hiko Sushi from Los Angeles".

I use GooglePlaces gem to retrieve data. For querying I use

GooglePlaces::Client.new(KEY).spots_by_query(keyword, options)  

where options is a hash that contains latitude, longitude, rankby='distance' and a radius.

Sidekiq activerecords sporadically get nil

Posted: 19 Apr 2016 05:18 AM PDT

I am running sidekiq jobs on a few models (ARs). Sometimes, sporadically, I am getting exceptions of nil models. That is, the models (which can be very old in the DB) are nil. I have IF conditions before the job to allow only when NOT nil, the code passes, but sometimes it gets the nil somewhere in the code.

I do not have reaping policy (using the default) in the database.yml, thus I am not sure why this is happening.

When I am retrying the jobs (even after a few seconds) - they succeed.

What can cause this break inside the job???

Thanks

javascript: How to prevent abusive use of public api

Posted: 19 Apr 2016 05:25 AM PDT

I am allowing user to login to my site on the basis of one time password send to the users mobile number.

My problem is that i am doing Api call to send otp to user's mobile number using jquery ajax. Now anyone can see the api call and make infinite api request to my server which will expire my sms pack immediately.

How can i avoid such abusive use of API call?

Addding additional properties to a Chart JS dataset

Posted: 19 Apr 2016 05:18 AM PDT

I'm trying to add extra properties to a Chart JS dataset (for a Pie / Doughnut chart). I've got a piece of Ruby on the back-end that prints the following JSON to the view:

[  {"segment": "undetermined",  "label": "Undetermined",  "value": 420193,"   color": "#DECF3F",  "highlight": "#e2d455"  },  {"segment":"peer_review",  "label":"Peer Review",  "value":415212,  "color":"#60BD68",  "highlight":"#72c479"  }  ]  

The "segment" property is an additional one (not provided for by the library) that I want to make available to my JS on the front-end. However when I wrap this JSON in a canvas tag I can't access it through JS.

The second line below outputs the above JSON:

<canvas id="review-type" height="235" data-facet="review_status_s">    <%= @by_review_type %>   </canvas>  

And I'm trying to access the "segment" property by using the getSegmentsAtEvent() API call (name collision accidental):

   $("#review-type").click(      function(evt) {        var activePoints = reviewChart.getSegmentsAtEvent(evt);          /* extract other properties, then build an URL from them: */          var url = "/" +locale+ "/catalog?f[" +facet_frag+ "][]=" +segment+ "&q=*:*";        window.location = url;      }    );  

However when I inspect activePoints in the JS console, "segment" isn't on the list of properties.

What should I do? Thanks.

No comments:

Post a Comment