Saturday, May 21, 2016

ruby on rails: exporting DB from development to production | Fixed issues

ruby on rails: exporting DB from development to production | Fixed issues


ruby on rails: exporting DB from development to production

Posted: 21 May 2016 06:33 AM PDT

Hi I'm using the gem yaml_db to export my development database from postgres to production, which is on a virtual machine where my ruby on rails app is.

So im using rake db:data:dump RAILS_ENV=development to create data.yml and rake db:data:load RAILS_ENV=productionto import the data, but i'm getting erros in importing.

rake aborted!  ActiveRecord::StatementInvalid: PG::InFailedSqlTransaction: ERROR:  current transaction is aborted, commands ignored until end of transaction block  : DELETE FROM "improvement_actions"    PG::FeatureNotSupported: ERROR:  cannot truncate a table referenced in a foreign key constraint  DETAIL:  Table "comments" references "improvement_actions".  

anyone knows how to solve this? Or is there other method to export my database?

Uncaught Error: Unknown provider: $controllerProvider from Students

Posted: 21 May 2016 06:33 AM PDT

I am using angular js in my rails application. When I land on my page, it works well but when I navigate in the app and come back on the same page, everything collapses. Upon 'inspect element' i found this error:

angular.min.js:26 Uncaught Error: Unknown provider: $controllerProvider from Studentsr  

I used all solutions available on stack overflow but problem is still there. kindly help. here is my code. If you need to know something else, please let me know.

 <div class = "animated fadeIn" ng-app="Studentsr" ng-controller="StudentCtrl">  <div id="dashboard-con">    <div>      <ng-view></ng-view>      <div class="dashboard-left-cell">        <div class="admin-content-con">          <header class="clearfix">            <div class = "divider pull-left">            <strong><h5 class="pull-left page_title">All Students</h5></strong>            <input type="text" ng-model="searchString" placeholder="Search Students"/>            <div class = "divider pull-right">              <%= form_tag :controller => :students, :action => :export do %>              <%= submit_tag "Download in Excel", class: "btn btn-xs btn-primary pull-right", id: "export" %>              <% end %>             </div>            <%= link_to "Add new Student", users_path( :admin => "student_add" ), :class => "btn btn-xs btn-primary pull-right", :role => "button" %>          </header>          <table class="table table-striped">          <thead>            <tr>                <th><%=  link_to :sort => "name", :admin => "students_view" do %>              <strong><font size="3"> Name </font></strong></span><span class="glyphicon glyphicon-sort-by-alphabet" aria-hidden="true"><% end %></th>              <th><%=  link_to :sort => "tracking_id", :admin => "students_view" do %>              <strong><font size="3"> Tracking ID </font></strong></span><span class="glyphicon glyphicon-sort-by-order" aria-hidden="true"><% end %></th>                          <th><%=  link_to :sort => "matric_percentage", :admin => "students_view" do %>              <strong><font size="3"> Matric %age </font></strong></span><span class="glyphicon glyphicon-sort-by-order" aria-hidden="true"><% end %></th>                          <th><%=  link_to :sort => "monthly_income", :admin => "students_view" do %>              <strong><font size="3"> Income </font></strong></span><span class="glyphicon glyphicon-sort-by-order" aria-hidden="true"><% end %></th>                          <th><%=  link_to :sort => "section", :admin => "students_view" do %>              <strong><font size="3"> Section </font></strong></span><span class="glyphicon glyphicon-sort-by-alphabet" aria-hidden="true"><% end %></th>                <th>Gender</th>              <th>City</th>              <th>Actions</th>            </tr>          </thead>          <tbody>            <tr ng-repeat="student in students | searchFor:searchString">                <td>{{student.name}}</td>                <td>{{student.tracking_id}}</td>                <td>{{student.matric_percentage}}</td>                <td>{{student.monthly_income}}</td>                <td>{{student.section}}</td>                <td>{{student.SEX}}</td>                <td>{{student.city}}</td>                <td>                  <%= link_to 'Edit', URI::unescape(users_path(:id => '{{student.id}}',:admin => "student_edit")), :class => 'btn btn-xs btn-warning', :role => "button" %>                  <%= link_to 'View', URI::unescape(users_path(:id => '{{student.id}}',:admin => "student_view")), :class => 'btn btn-xs btn-primary', :role => "button" %>                  <%= link_to 'Delete', URI::unescape('students/{{student.id}}'), method: :delete, :class => 'btn btn-xs btn-danger', :role => "button", :data => {confirm: 'Are you sure you want to delete this?'} %>                </td>            </tr>          </tbody>        </table>      </div>    </div>  </div>  

javascript, which i have written right below this html

  <script>  var stdMod = angular.module('Studentsr', []);   stdMod.controller('StudentCtrl', function ($rootscope) {    $scope.students = []    <% if @students!=nil%>      <% @students.each do |student| %>        $scope.students.push({          id: '<%= student.id %>',          name:'<%= student.name %>',          tracking_id: '<%= student.tracking_id %>',          matric_percentage: '<%= student.matric_percentage %>',          monthly_income: '<%= student.monthly_income %>',          section: '<%= student.section %>',          SEX: '<%= student.SEX%>',          city: '<%= student.city%>'        })      <% end %>    <% end %>  });  stdMod.filter('searchFor', function(){    return function(arr, searchString){      if(!searchString){        return arr;      }      var result = [];      searchString = searchString.toLowerCase();      angular.forEach(arr, function(item){        if(item.name.toLowerCase().indexOf(searchString) !== -1){          result.push(item);        }else if(item.tracking_id.toLowerCase().indexOf(searchString) !== -1){          result.push(item);        }else if(item.matric_percentage.toLowerCase().indexOf(searchString) !== -1){          result.push(item);        }else if(item.monthly_income.toLowerCase().indexOf(searchString) !== -1){          result.push(item);        }else if(item.section.toLowerCase().indexOf(searchString) !== -1){          result.push(item);        }else if(item.SEX.toLowerCase().indexOf(searchString) !== -1){          result.push(item);        }else if(item.city.toLowerCase().indexOf(searchString) !== -1){          result.push(item);        }      });      return result;    };  });  </script>  

any help will be highly appreciated.

Why Rails defaults creation to a POST on collection in HTML form?

Posted: 21 May 2016 06:15 AM PDT

When generating a scaffold, by default the new_resource_path generates a form that will submit to resources_path.

This makes total sense in a RESTful mentality.

But, given that the generated material does not uses it as a REST resource, why does it POST to the collection path?

When the resource is successfully created, Rails will redirect to the created resource path. When any error occurs, Rails will render the new template that will present the errors (generated by scaffolding).

This seems fine, except that when any errors occurs when trying to create the resource, the URL will change to the collection path. This means that if user tries to refresh the page, it will not see the creation form. If the application does not allow listing for this resource, a routing error may happen. In case the application uses any type of authorization and the current user does not has the required authorization to list stuff, it may see a forbidden.

I see Rails scaffold generator as something the community agrees to be the standard way to do basic CRUD in it. So, why this behavior?

It seems that by keeping a purist RESTful resources approach we are breaking user experience a bit.

To see an example of this, just create a new Rails application, scaffold a new entity and try to create it with some validation errors.

$ rails new example  $ cd example  $ rails generate scaffold note text  # edit app/models/note.rb    class Note < ApplicationRecord     validates :text, length: { minimum: 10 }    end  $ rails db:migrate  $ rails server  # go to localhost:3000/notes/new  # click 'Create Note'  # see the error  # hit browser's refresh button  # now you are listing notes, and not creating one  

If you think "this should not harm a real application". I've come up with this when writing tests for authentication.

My application is using Devise and fails for this test:

test 'new user should not be able to register with wrong password confirmation' do    email = 'newuser@newdomain.com'    password = 'little$secret'    password_confirmation = 'big$secret'      visit new_user_registration_path    fill_in 'Email', with: email    fill_in 'Password', with: password    fill_in 'Password confirmation', with: password_confirmation      assert_no_difference ->{ User.count } do      click_on 'Sign up'    end      assert page.has_content?("Password confirmation doesn't match Password")    # FAILS:    assert_equal new_user_registration_path, current_path  end  

What this means in real life: When user tries to create an account, submit an invalid form, see the error and hit refresh, it is on an invalid path as the resource does not support listing (i.e. /users).

To make that last assertion pass, I had to overwrite the default Devise view to submit the form to /users/sign_up instead of just /users and to add a new route to call create when a POST is made to this URL. Then I realized that this will happen to any controller following the RESTful Resource approach, unless developers create this new route and use a custom URL for submitting creation forms.

My bet is that I'm missing something, but I can't figure it out. So, what am I missing?

Complexe authorization system

Posted: 21 May 2016 06:06 AM PDT

I've to develop a complexe authorization system for a JSON API, but I don't know how to proceed. The possible permissions have to be dynamic. I'll have a dashboard to allow / disallow access to resource.

I've a Company with Company::Member. Each Company::Member have a Job, a Division and a JobLevel.

This can be sum up with the following model:

# == Schema Information  #  # user_id       :integer  # company_id    :integer  # job_id        :integer  # division_id   :integer  # job_level_id  :integer  # ==========================    class Company::Member < AR::Base  end  

The Permission of the Company::Member are determined by the triplet [job_id, division_id, job_level_id].

Here's my problem:

If someone access the URL /company/:company_id/members, I want to be able to authorize:

  • users who are members of the :company_id and has a member have a triplet [job_id, division_id, job_level_id], that have a role that allow the show of members (brainfuck :()
  • users who are authorized to see any members of any company, because they belongs to to a specific company (which is fix and known), and have a triplet [job_id, division_id, job_level_id] that have a role that allow the show of members (second brainfuck)

I first came with the idea to give a Authorization::Role to each triplet [job_id, division_id, job_level_id], and each Authorization::Role has a set of Authorization::Permission such as:

Authorization::Permission.create(    name: 'See Company::Member if member',    value: 'company/member::show::is_member'  )    Authorization::Permission.create(    name: 'See Company::Member for all company',    value: 'company/member::show::*'  )  

In my controller, I can have:

class Company::MembersController    # GET /companies/:company_id/members    def index      authorize!(current_user, class: Company::Member, company_id: params[:company_id], action: :index)    end  end  

Do you know if there any pattern / gem that can help me create that kind of system ?

Rails keeps putting text onto my page within {} and [], how do i get rid of this?

Posted: 21 May 2016 06:44 AM PDT

This is an example of the outputted text, when inspected using dev tools, it's listed under text

[#]

http://imgur.com/XLjAcPH

Rails tutorial: delete method doesn't work

Posted: 21 May 2016 05:34 AM PDT

I'm following instructions of this tutorial: http://guides.rubyonrails.org/getting_started.html I have a problem with deleting articles. I've written the code as the tutorial suggests, and link 'Destroy' has appeared, but when I click it, instead of asking me for a confirmation and deleting the article, it shows me the article's page, i.e. it does exactly the same thing as when I click on 'Show'. This is the place in my code that fails to perform what I want it to:

<td><%= article.title %></td>          <td><%= article.text %></td>          <td><%= link_to 'Show', article_path(article) %></td>          <td><%= link_to 'Edit', edit_article_path(article) %></td>          <td><%= link_to 'Destroy', article_path(article),            method: :delete,            data: { confirm: 'Are you sure?' } %></td>  

I'd appreciate any help!

The destroy method inside the ArticlesController:

def destroy      @article = Article.find(params[:id])      @article.destroy      redirect_to articles_path, alert: "Article successfully deleted"  end  

routes.rb:

Rails.application.routes.draw do      get 'welcome/index'      resources :articles      root 'welcome#index'  end  

How do I check if an element exists inside a jQuery plugin?

Posted: 21 May 2016 04:59 AM PDT

My question is pretty self explanatory - I'm writing a jQuery plugin where the user specifies a selector. I need to check if that selector exists, and if so, execute some code. However, I can't figure out how to do that check inside of my jQuery plugin.

I need to do this because I'm trying to create something like jquery-readyselector (https://github.com/Verba/jquery-readyselector) that works with Turbolinks.

I want to be able to use the function like so:

$("#mySelector").pageReady(function() {      // This is only triggered if #mySelector exists.      console.log('test')  });  

Here's my attempt:

(function($) {    $.fn.pageReady = function(fn) {      var that = this;      $(document).on('ready page:load', function() {        if (that.length <= 0){          return        } else {          fn();        }      });    }   })(jQuery);  

The issue with this is that that.length == 0, even if the element exists.

I also tried defining the function inside a 'ready page:load' but I get pageReady is not a function:

$(document).on('ready page:load', function() {    $.fn.pageReady = function(fn) {      if (this.length <= 0) {        return      } else {        fn();      }    }  });  

Note that I'm using Turbolinks with Rails, and that's why I have that $(document).on('ready page:load' ...). Replacing that line with $(document).ready(...) would do the same thing in a non-Rails/Turbolinks app.

Pushing Rails app to Heroku seeing no difference on asset files

Posted: 21 May 2016 05:12 AM PDT

I have searched over the web & stackoverflow about this topic but could not find a comprehensive guide even in heroku's web site.

I have a rails app and when I push the app to heroku here are the steps I am following;

  1. rake assets:clobber
  2. bundle exec rake assets:precompile RAILS_ENV=production
  3. git init
  4. git add .
  5. git commit -m "message"
  6. git push heroku master

Voila!, but then when I make changes in js and/or css files, I start again from number 1 deleting assets then precompile etc as I mentioned. But sometimes I can not see the differences I make on heroku. When I destroy the heroku app and push again there I see.

I am wondering, whether I have to clean Heroku assets as well like rake assets:clobber.

Some people say that when you push to Heroku, it resets asset files automatically but then what is the reason sometimes I can not see the differences.

When committing to git git commit -m "message" do you think this message part must be unique?, maybe when commit with the same message, they create a conflict ?

Thank you

URL slugs for nested resources

Posted: 21 May 2016 05:28 AM PDT

In my rails app my models include user, item, and user_item.

user.rb

has_many :user_items  has_many :items, through: :user_items  

item.rb

has_many :user_items  has_many :users, -> { uniq }, through: :user_items  belongs_to :user  

user_item.rb

belongs_to :user  belongs_to :item  

Names for items should never change and cannot be edited by users.

A URL for a user would be /users/:id. A URL for an item, would be /items/:name for SEO and user-friendly purposes.

But what would be best for user_item? Some possibilities:

/users/:id/items/:name

/user_item/:id

/user_item/:item_name

/user_item/:id/:item_name

Storing and Retrieving postgres nested JSONB data type in rails form

Posted: 21 May 2016 06:31 AM PDT

I realised there is not much information about how to use rails form to store and retrieve JSON type data. I am currently facing the following problem:

I have a form that creates a nested structure in JSON:

= form_for(@car) do |cf|      = cf.fields_for :locations do | locations_f |          = locations_f.fields_for :primary_location do | primary_location_f |              .sm-col.md-col.sm-col-6.px2                  label.inline-block.mb1 District                  = primary_location_f.text_field :district               .sm-col.md-col.sm-col-6.px2                  label.inline-block.mb1 Street                  = primary_location_f.text_field :street   

It will generate input HTML tags as such:

<input name="car[locations][primary_location][district]">

<input name="car[locations][primary_location][street]">

I am able to persist it in database after doing params.permit:

params.require(:car).permit([      locations:[primary_location:[:street, :district]]  ])  

I also create store_accessor in the model

store_accessor :locations, :primary_location, :other_locations  

However, after I persisted the data, I want it to be shown in the text_field what is already persisted in the database. I try to do something like:

= primary_location_f.text_field :district, value: @car.locations['primary_location']['district']  

However, it will run into NilClass Error as sometimes @car.locations['primary_location'] may be nil, and error will arise when I call @car.locations['primary_location']['district'].

I wonder what is the best way to store and retrieve JSON data type. And what is a good way when the JSON is nested.

Thanks

Method returns an Array object

Posted: 21 May 2016 06:22 AM PDT

My database is PostgreSQL. I'm using the following code to eliminate duplicate rows from a table:

uniqBk = Bikehistory.all(      :select => 'DISTINCT ON (bikehistories.bike_numbers) *',      :order => 'bikehistories.bike_numbers'  )  

Unfortunately the returning object is class of Array instead of ActiveRecord::Relation::ActiveRecord_Relation_Bikehistory.

How can I get an ActiveRecord object and get the same query results?

Delaying Mail with ActiveJobs won Rails 4.2

Posted: 21 May 2016 06:02 AM PDT

Looking at ActiveJob to delay mailer tasks (using delayed_jobs, delayed_jobs_active_record) and I have 2 questions about:

  • ActiveJob's ActionMailer's deliver_later method
  • If a job can have multiple perform methods

I have a Post model that requires email sent to moderators if it's updated and deleted.

# Post Model  class Post < ActiveRecord::Base  # Table name: posts  #  #  id         :integer  #  title      :string   #  body       :text             #  created_at :datetime  #  updated_at :datetime      before_save :email_mod_post_updated, :email_mod_post_deleted      private        def email_mod_post_updated        ModeratorMailerJob.updated_post_email(self).deliver_later      end        def email_mod_post_deleted        ModeratorMailerJob.deleted_post_email(self).deliver_later      end  end    # ModeratorMailer  class ModeratorMailer < ApplicationMailer    default from: "Mod <mod@domain.com>"      def updated_post_email(post)      @post = post      mail(to: "mod@domain.com", subject: "Post Updated - #{@post.title}")    end      def deleted_post_email(post)      @post = post      mail(to: "mod@domain.com", subject: "Post Deleted - #{@post.title}")    end  end  

Current ActiveJob setup:

# app/jobs/updated_post_email_job.rb  class UpdatedPostEmailJob < ActiveJob::Base    queue_as :default      def perform(post)      ModeratorMailer.updated_post_email(post)    end  end    # app/jobs/deleted_post_email_job.rb  class DeletedPostEmailJob < ActiveJob::Base    queue_as :default      def perform(post)      ModeratorMailer.deleted_post_email(post)    end  end  

Question 1: With the deliver_later method, does this still relay on setting up an ActiveJob eg. app/jobs/updated_post_email_job.rb or is this not required (I have delayed_job running in the background)?

Would this be the same as calling ModeratorMailerJob.perform_later(post)

Question 2: Do people add multiple perform methods in their active jobs eg:

class EmailModeratorJob < ActiveJob::Base    queue_as :default      def perform(post)      ModeratorMailer.updated_post(post)    end        def perform(post)      ModeratorMailer.deleted_post(post)    end  end  

or is it best to have seperate jobs for a particular task?

Image galleries in Rails

Posted: 21 May 2016 06:05 AM PDT

I'm wondering what the best design for the following would look like in Rails:

A website with three different image galleries, let's say one showing pictures of the company's staff under mywebsite.com/gallery, another one shows pictures of product A at mywebsite.com/productA and the third shows product B under mywebsite.com/productB.

I assume it would be bad design to create a gallery resource, along with a productA and a productB resource since there will be only one of each and it's really the new photos and not new image collections which will have to be created.

So I'm thinking if it's a good idea to create an images resource and then use single table inheritance, instantiate a gallery_images, productA_images and productB_images and change the routes to the respective ones which I want to show up as URLs. I should probably mention that I don't want to mix up the images for the different sections.

I feel there must be a "proper" way of doing this, I guess tons of websites use a similar scheme.

rails will_paginate with different partials

Posted: 21 May 2016 03:40 AM PDT

I have some new actions for the notification model and things started getting messy so I refactored from <% = render @other_notifications %> with notifcations/_notification.html.erb to the following structure.

My problem is the following. The page renders everything well, but the pagination doesn't work properly. So IF I have the structure below and doesn't delete _notification.html.erb then the page will be loaded with the new action partials and the pagination objects will be loaded with _notification.html.erb. IF I delete _notification.html.erb then the page still loads with the new partials, but pagination doesnt't work. How should I change the pagination to make this work?

notifications_controller.rb

def other_notifications    @other_notifications = current_user.notifications.not_chat.order(created_at: :desc).includes(:sender_profile).                           paginate(page: params[:page], per_page: Notification.pagination_per_page)    current_user.reset_new_other_notifications    respond_to do |format|      format.html      format.js    end  end  

other_notifications.html.erb

<div class = "other-notifications-index">    <% @other_notifications.each do |notification| %>      <% if lookup_context.template_exists?(notification.action, "notifications/actions", true) %>        <%= render partial: "notifications/actions/#{notification.action}", locals: { notification: notification } %>      <% end %>    <% end %>  </div>  <div id="infinite-othernotification-scrolling">    <%= will_paginate @other_notifications %>  </div>  

other_notifications.js.erb

$('.other-notifications-index').append('<%= j render @other_notifications %>');  <% if @other_notifications.next_page %>    $('.pagination').replaceWith('<%= j will_paginate @other_notifications %>');  <% else %>    $(window).off('scroll');    $('.pagination').remove();    $('.no-more').delay(1000).fadeIn(1500);  <% end %>  

Override Spree 3 Registration Controller

Posted: 21 May 2016 03:25 AM PDT

Been searching the web for a simple documentation on this task but no avail. I need not to add another model for this. Basically I need to override the spree registration controller and use its user model.

All I need to to do, on a custom page, I have a spree login/signin/registration button/link. That will then go to my custom controller to create a new user based on if statements:

if ( Spree::User.find_by(email: "spree@example.com") )    # do stuffs  else    #create new spree user  end  

Then later I modify the spree session controller to know which url the user comes from to redirect. Simple huh? Any docs on this? I'm not looking for this.

I'm using Rails 4.2.6

Spree 3.1.0.rc3

Can't install gem nokogiri with 2.3.0p ruby

Posted: 21 May 2016 03:08 AM PDT

Welcome, I tried to install gem mechanize and got stuck at nokogiri gem. Then I tried to install nokogiri gem and got stuck also. Here is my CMD, this doesn't make sense ;/

>ruby -v  ruby 2.3.0p0 (2015-12-25 revision 53290) [x64-mingw32]    >gem install nokogiri  ERROR:  Error installing nokogiri:          nokogiri requires Ruby version < 2.3, >= 1.9.2.  

how to make this code drier

Posted: 21 May 2016 03:55 AM PDT

I am wondering if it is possible to make this code even simpler. I am worried t be hitting the database too many times with the same query. Here is my code:

#hot-panel.mdl-tabs__panel.is-active   %ul.product-list-three.mdl-list    - @merchant.products.where('products.prototype_id = 1').select(&:id).flatten.uniq.each do |item|     = render :partial => 'product', :locals => {:item => item }  #cold-panel.mdl-tabs__panel   %ul.product-list-three.mdl-list    - @merchant.products.where('products.prototype_id = 2').select(&:id).flatten.uniq.each do |item|     = render :partial => 'product', :locals => {:item => item }  

Here are the logs:

Product Load (1.1ms)  SELECT "products".* FROM "products" INNER JOIN "variants" ON "products"."id" = "variants"."product_id" INNER JOIN "variant_merchants" ON "variants"."id" = "variant_merchants"."variant_id" WHERE "variant_merchants"."merchant_id" = $1 AND (products.prototype_id = 1)  [["merchant_id", 1]]  default_url_options is passed options: {}      Rendered shopping/merchants/_product.html.haml (3.5ms)    Product Load (1.2ms)  SELECT "products".* FROM "products" INNER JOIN "variants" ON "products"."id" = "variants"."product_id" INNER JOIN "variant_merchants" ON "variants"."id" = "variant_merchants"."variant_id" WHERE "variant_merchants"."merchant_id" = $1 AND (products.prototype_id = 2)  [["merchant_id", 1]]    Rendered shopping/merchants/_product.html.haml (0.5ms)  

Models Merchant

 has_many :variant_merchants   has_many :variants, through: :variant_merchants, dependent: :destroy   has_many :products, through: :variants, dependent: :destroy  

Product

 belongs_to :prototype   has_many :product_properties   has_many :properties, through: :product_properties     has_many :variants, dependent: :destroy  

Variant

 has_many :variant_merchants, dependent: :destroy   has_many :merchants, through: :variant_merchants     has_many :variant_properties   has_many :properties, through: :variant_properties  

Product Partial

= link_to shopping_merchant_product_path(@merchant, item.id) do    %li.mdl-list__item.mdl-list__item--three-line      %span.mdl-list__item-primary-content        %span= item.name        %span.mdl-list__item-text-body          = item.description      %span.mdl-list__item-secondary-content        %i.material-icons          chevron_right  

Create an excel in delayed job method using axlsx

Posted: 21 May 2016 03:51 AM PDT

I am trying to generate an excel file in my delayed job method in model. which is working fine in local. i'm using scheduler to run delayed jobs in heroku. Jobs are getting finished successfully without generating excel.

my delayed job method looks like:

def self.generate_excel       Axlsx::Package.new do |p|      p.workbook.add_worksheet(:name => "Stock Details") do |sheet|         sheet.add_row ["S.No",  "ProductId", "Title"]         products.each_with_index do |prods, index|         sheet.add_row ["1", "1234", "product title"]                  end              end     p.serialize("#{Rails.root}/app/views/stock_details/stock_details.xlsx")  end  

I'm using delayedjob 4.1.

Oauth2 access to API by email/password

Posted: 21 May 2016 04:09 AM PDT

I use gem 'rack-oauth2-server'. Currently I need add access to API by email/password from mobile app.

About problem: Gem provide access token from 'oauth/access_token' endpoint. This require next parameters: 'email', 'password', 'client_id', 'secret'. 'client_id' and 'secret' - fields of oauth client from mongodb collection. Client have setting to scope access. I have few user types. For each user type be different access scope(different oauth clients).

So, a problem: I want allow get access to api from mobile app for any user type, but, before login, i don't know which type have user. So, mobile app can't know which client_id and sercret should be passwed to 'oauth/access_token' request.

Maybe exist some pre-hook for rails requests or another method for add params to request on fly(server side)? Note: before_filter not can be used, because 'rack-oauth2-server' called before callbacks.

P.S. Excuse me for my bad English.

How to have javascript files included only on certain pages

Posted: 21 May 2016 12:13 AM PDT

I have a WYSIWYG editor that I have built into the site and customised. There are a lot of js files that only need to be loaded on the pages with the WYSIWYG editor and currently thay are loaded on every page (and even break other js certain pages).

Currently the js files are in assets/javascript/wysiwyg/ and aren't included as the require files in appliction.js but are still included on every page because of the assets pipeline (I think).

I want to know if I can exclude these files from the other pages. Maybe have them removed from the assets pipeline and put the in the public directory or something and have an import statement in the coffee script files associated to the views I want them in. I'm fairly new to rails so I dont know how it all works 100%.

Is something like this possible and if so how would I go about doing it?

In Rails app, jQuery click handler stops working after clicking link to go back

Posted: 21 May 2016 04:13 AM PDT

I have a page function_a.html.erb to display some images. I defined a class liimg and call a jQuery to detect a click event on an image.

Everything is fine and when an image is clicked I have the desired page function_b.html.erb displayed.

The problem occurs when I go back to the function_a page with <%= link_to 'back', :back %> – after this, the click on images is no longer detectable.

Am I missing something? But what? Help is welcome.

Incrementing dynamic variables in Rails models

Posted: 21 May 2016 12:04 AM PDT

I am a new RoR user having problems creating non database attributes on my models. The below is the basics of what I'm trying to do, using php code.

class User{    $count = 0      function increment() {      for($x = 0, $x < 10, $x++) {        $count++      }    }  }  

I want to be able to access the $count attribute in my view.

This is what I've come up with using ruby. People on sailing needs to be dynamically counted for each sailing.

class Sailing < ActiveRecord::Base  ... active record associations ...    attr_accessor :people_on_sailing    def people_on_sailing    @people_on_sailing  end    def people_on_sailing=(val)    inc = val + 1    @people_on_sailing = inc  end    def increment    self.travelling_parties.each do |party|      # *** Somehow increment people_on_sailing ***      puts people_on_sailing=(1)    end  end  

What I would really like to do is call sailing.people_on_sailing, after putting 'increment' in some sort of constructor. Is something like this possible?

How to run capistrano tasks over lossy connection?

Posted: 21 May 2016 05:13 AM PDT

Is it possible to run a capistrano task over a lossy connection?

E.g. if the internet drops out or your disconnect wifi, it will resume the command/task when you're back online.

I am using capistrano v3x.

Thanks,

Why Rails 5 uses ApplicationRecord instead of ActiveRecord::Base?

Posted: 21 May 2016 12:43 AM PDT

We know that Rails 5 added ApplicationRecord as an abstract class which was inherited by our models (ActiveRecord).

But basically, I think every technical requirement we do with ApplicationRecord, we can also do with ActiveRecord::Base. For instance:

module MyFeatures    def do_something      puts "Doing something"    end  end    class ApplicationRecord < ActiveRecord::Base    include MyFeatures    self.abstract_class = true  end  

So now every model will be attached the behaviors of MyFeatures. But we can also achieve this in Rails 4:

ActiveRecord::Base.include(MyFeatures)  

So what is the benefit of using ApplicationRecord, do you think it is necessary to add ApplicationRecord?

uninitialized constant EventController::TempFile

Posted: 20 May 2016 11:13 PM PDT

I am trying to create a temp file in my rails application. Here is the controller code:

private  def tmp_example   temp_file = TempFile.new('logo')   # save uploaded file   File.open(temp_file.path, "w") do |f|     f.write session[:user_params]["logo"].delete(:file).read     f.close   end  end  

I have required the tempfile in application.rb

require 'tempfile'  

But still i am getting error:

uninitialized constant UsersController::TempFile

Can anyone how to fix this issue thanks.

Setting up a rake task with Resque Scheduler - Rails 4

Posted: 20 May 2016 11:57 PM PDT

I am on Rails 4 using the Resque Scheduler gem.

I am also using the sitemap generator gem in order to dynamically generate my sitemap.

I am having trouble figuring out the best way to schedule a rake task with resque scheduler. The sitemap generator recommends whenever, but I am assuming resque scheduler can accomplish the same thing (don't want to install another gem if I don't have to).

Does anyone know how to set this up?

I would like to run rake sitemap:refresh:no_ping every 5 hours.

I was thinking I would just schedule a background job and run it from there:

# resque_schedule.yml    update_sitemap:    every: 5h    class: "SitemapUpdater"    description: "This job refreshes the sitemap"        # sitemap_updater.rb    class SitemapUpdater      @queue = :sitemap_queue      def self.perform      # run rake task here    end    end  

... however, I'm not sure if this is a good practice. Any advice would be much appreciated.

Nested throttle for API in rails

Posted: 20 May 2016 10:37 PM PDT

I know there is a lot of gems around throttling API requests in rails, but the problem is their structure is pretty flat - I mean you cannot apply another rule based on other rule happening. Here is the example:

throttle max: 100, per: 1.day

cool, but what if I want to reduce the number of those requests after reaching 100 per day to for example 10 per hour?

so something like:

throttle max: 100, per: 1.day do throttle max: 10, per: 1.hour end

how to achieve that with the use of existing gems avoiding custom solutions as much as possible?

Rails: Bundle install not working

Posted: 20 May 2016 09:33 PM PDT

I've generated the app with "rails new" and switched to that directory but when I try to use "bundle install" I get

An error occurred while installing debug_inspector (0.0.2), and Bundler cannot continue. Make sure that gem install debug_inspector -v '0.0.2' succeeds before bundling.

any suggestions? I'm on OS X if that helps for some reason

How to get time x days ago from a specific date in Rails?

Posted: 20 May 2016 10:03 PM PDT

I am looking for a rails solution to calculate the time ago from a particulat time. For example , 2 days ago 15th May 2016 22:00 UTC should return 13th May 2016 22::00 UTC .

My requirement is something like this

2.days.ago.from(yesterday)   

Which will be a more specific version of

2.days.from_now  

Rails - establish_connection and nested forms

Posted: 21 May 2016 06:00 AM PDT

I'm having a problem creating a nested model with establish_connection using another database.

class Restaurant < ActiveRecord::Base    establish_connection :'f7-api'      has_many :sections, dependent: :destroy    has_many :items, through: :sections    accepts_nested_attributes_for :sections, allow_destroy: true  end    class Section < ActiveRecord::Base    establish_connection :'f7-api'      belongs_to :restaurant    has_many :items, dependent: :destroy    has_many :options, through: :items    accepts_nested_attributes_for :items, allow_destroy: true  end  

-

PG::ForeignKeyViolation: ERROR: insert or update on table "sections"   violates foreign key constraint "fk_rails_14e0e2a999" DETAIL: Key   (restaurant_id)=(3) is not present in table "restaurants". : INSERT INTO   "sections" ("title_input_id", "restaurant_id", "created_at",   "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  

The form parameters from the action are (formatted):

{    "utf8"=>"✓", "authenticity_token"=>"FLe24nnI3fITIS4bpMBDjJ0Ne+F0S3Rh9HgjYIqotR3CpbT/gHa0c3iQi‌​0yUtiCQNdNBYi0ANN75fqiZU6japw==",     "restaurant"=>{      "name"=>"asd", "business_name"=>"", "cnpj"=>"", "description"=>"",       "url"=>"", "phone"=>"", "mobile"=>"", "website"=>"",      "sections_attributes"=>{        "1463797768730"=>{"title"=>"", "_destroy"=>"false"}      }    },     "commit"=>"Save Restaurant"  }  

restaurants_controller

  # POST /restaurants    # POST /restaurants.json    def create      @restaurant = Restaurant.new(restaurant_params)        respond_to do |format|        if @restaurant.save          format.html { redirect_to @restaurant, notice: 'Restaurant was successfully created.' }          format.json { render :show, status: :created, location: @restaurant }        else          format.html { render :new }          format.json { render json: @restaurant.errors, status: :unprocessable_entity }        end      end    end    def restaurant_params        params.require(:restaurant).permit(          :id,          :name,          :business_name,          :cnpj,          :description,          :phone,          :mobile,          :website,          :user_id,          :street,          :complement,          :number,          :lat,          :lng,          :zip_code,          :neighborhood_id,          :city_id,          :state_id,          :country_id,          photos: [:id, :image, :main],          open_hours: [:id, :weekday, :opens_at, :closes_at],          cuisine_ids: [],          category_ids: [],          sections_attributes: [            :id,            :title,            :restaurant_id,            :_destroy,            items_attributes: [              :id,              :title,              {:description => []},              :section_id,              :price_cents,              :not_equal,              :_destroy,              options_attributes: [                :id,                {:description => []},                :item_id,                :price_cents,                :_destroy              ]            ]          ]        )      end  

No comments:

Post a Comment