Monday, November 21, 2016

Mobile CSS view not working on Heroku, although working locally + popular fixes attempted | Fixed issues

Mobile CSS view not working on Heroku, although working locally + popular fixes attempted | Fixed issues


Mobile CSS view not working on Heroku, although working locally + popular fixes attempted

Posted: 21 Nov 2016 08:20 AM PST

I'm working on an app forked from https://github.com/jcs/lobsters and am having a heck of a time getting mobile css updated views on heroku. Everything is working locally.

Here are the steps I've crossed off so far: Ran this (several times):

Run bundle exec rake assets:precompile on your local code  

Updated my prod environment like this:

config.cache_classes = true  config.serve_static_assets = true  config.assets.compile = true  config.assets.digest = true  

The application and mobile stylesheets both end in .css.

My mobile selector (not that I think it matters since it's working locally) is:

@media only screen and (max-width: 480px) {      html {          -webkit-text-size-adjust: none;      }   .....  

I've also restarted heroku a couple times and viewed page(s) in incognito to make sure it wasn't a local caching issue. And I've also changed the application.css and those changes happened on heroku.

Appreciate any help. Thanks.

Rails automatically load lib from begining

Posted: 21 Nov 2016 08:23 AM PST

I create a awsmail.rb inside lib directory.

class AwsMail    def...  end  

However, when I called it on rails console, it threw this error.

pry(main)> AwsMail  NameError: uninitialized constant AwsMail  

I need to load this file by myself, so that it can be called.

Like this.

pry(main)> load "#{Rails.root}/lib/awsmail.rb"  => true  pry(main)> AwsMail  => AwsMail  

How do I make this file automatically being loaded?

How to save 2 documents in mongodb collection instead of 1?

Posted: 21 Nov 2016 08:14 AM PST

On rails console, I am trying to save 2 categories in my book class. However my output returns 1 category.

My code:

class Book    include Mongoid::Document    field :title, type: String    field :publisher, type: String    field :published_on, type: Date    field :votes, type: Array    belongs_to :author    has_and_belongs_to_many :categories    embeds_many :reviews  end      class Category    include Mongoid::Document    field :name, type: String    has_and_belongs_to_many :books  end      class Author    include Mongoid::Document    field :name, type: String    has_many :books  end  

Output on terminal

irb(main):001:0> b = Book.new(title: "Oliver Twist", publisher: "Dover Publications", published_on: Date.parse("2002-12-30") )    => #<Book _id: 5833129213197da7660c0adb, title: "Oliver Twist", publisher:       "Dover Publications", published_on: 2002-12-30 00:00:00 UTC, votes: nil,   author_id: nil, category_ids: nil>  irb(main):002:0> Author.create(name: "Charles Dickens")  => #<Author _id: 5833129a13197da7660c0adc, name: "Charles Dickens">    irb(main):003:0> Category.create(name: "Fiction")  => #<Category _id: 583312a113197da7660c0add, name: "Fiction", book_ids: nil>    irb(main):004:0> Category.create(name: "Drama")  => #<Category _id: 583312a813197da7660c0ade, name: "Drama", book_ids: nil>    irb(main):006:0*   irb(main):007:0* b.author = Author.where(name: "Charles Dickens").first  => #<Author _id: 5832d97713197da0893c05b9, name: "Charles Dickens">    irb(main):008:0> b.categories << Category.first  => [#<Category _id: 58330d7d13197da0893c05ba, name: "Fiction", book_ids:           [BSON::ObjectId('5832d96913197da0893c05b8'),    BSON::ObjectId('5833129213197da7660c0adb')]>]    irb(main):009:0> b.categories << Category.last  => [#<Category _id: 58330d7d13197da0893c05ba, name: "Fiction", book_ids:  [BSON::ObjectId('5832d96913197da0893c05b8'), BSON::ObjectId('5833129213197da7660c0adb')]>]    irb(main):010:0>   irb(main):011:0*     irb(main):012:0* b  => #<Book _id: 5833129213197da7660c0adb, title: "Oliver Twist", publisher:     "Dover Publications", published_on: 2002-12-30 00:00:00 UTC, votes: nil,    author_id: BSON::ObjectId('5832d97713197da0893c05b9'), category_ids:   [BSON::ObjectId('58330d7d13197da0893c05ba')]>    irb(main):013:0> b.save  => true    irb(main):014:0> Category.first  => #<Category _id: 58330d7d13197da0893c05ba, name: "Fiction", book_ids:    [BSON::ObjectId('5832d96913197da0893c05b8')]>    irb(main):015:0> Category.last  => #<Category _id: 58330d7d13197da0893c05ba, name: "Fiction", book_ids:    [BSON::ObjectId('5832d96913197da0893c05b8')]>  irb(main):016:0>   

both categories show name as 'fiction' not 'drama' futhermore, under testing -

> db.books.findOne()  {    "_id" : ObjectId("5833129213197da7660c0adb"),    "title" : "Oliver Twist",    "publisher" : "Dover Publications",    "published_on" : ISODate("2002-12-30T00:00:00Z"),    "author_id" : ObjectId("5832d97713197da0893c05b9"),    "category_ids" : [      ObjectId("58330d7d13197da0893c05ba")   ]  }  >   >   > db.categories.findOne()  {    "_id" : ObjectId("58330d7d13197da0893c05ba"),    "name" : "Fiction",    "book_ids" : [      ObjectId("5832d96913197da0893c05b8")    ]  }  

How do I ensure that 2 categorie_ids appear on db.books.findOne() ?

Will much appreciate your advice..

In rails "get 'vendors/keyword_search', to: 'vendors#keyword_search'" runs "'vendors#show'"

Posted: 21 Nov 2016 08:04 AM PST

In a rails app, I am trying to setup a route to a keyword search page. I am trying to pass the following test:

scenario 'can perform a keyword search' do    click_link 'Search'    click_link 'Keyword search'    expect(current_path).to eq '/vendors/keyword_search'    fill_in 'search', with: vendor_one.email    click_button 'Search suppliers'    expect(page).to have_content vendor_one.email    expect(page).not_to have_content vendor_two.email  end  

So far I have:

in /views/vendors/index.html.erb

<div class='col-xs-3'>    <p><%= link_to 'Keyword search', vendors_keyword_search_path %></p>  </div>  

in /routes.rb

root to: 'homepage#index'    resources :buyers, :vendors    get 'vendors/keyword_search', to: 'vendors#keyword_search'  

in /controllers/vendors_controller.rb

class VendorsController < ApplicationController    def index      @vendors = Vendor.all    end      def show      @vendor = Vendor.find(params[:id])    end      def keyword_search    end  end  

I then have a /views/vendors/keyword_search.html.erb with the following:

<div id='main container' class='container-fluid'>    <div class='row'>      <div class='col-xs-3'>      </div>      <div class='col-xs-6'>        <h1>suppliers#keyword_search</h1>      </div>      <div class='col-xs-3'>      </div>    </div>  </div>  

My issue seems to be coming after a click on the 'Keyword search' link. Rather than running vendors#keyword_search and loading the '/views/vendors/keyword_search.html.erb' template, my path helper vendors_keyword_search_path attempts to run vendors#show resulting in the following error message (note the first line of stack trace included):

1) Buyers searching vendors can perform a keyword search     Failure/Error: @vendor = Vendor.find(params[:id])       ActiveRecord::RecordNotFound:       Couldn't find Vendor with 'id'=keyword_search     # ./app/controllers/vendors_controller.rb:7:in `show'  

Help on this would be greatly appreciated, but most of all I really want to understand why it's running show and not keyword_search.

Thanks

Rails : dynamically add helper to controller and access it in view

Posted: 21 Nov 2016 07:29 AM PST

My code is as follows:

ac = ActionController::Base.new()  # do some stuff  ac.render_to_string(    partial: my_partial,    formats: my_format,    locals: { some_local: some_value }  )  

What I would like to do is make some helpers dynamically available to the partial that I render. Ideally, I'd like to loop over an array of helper modules and extend the view so that my helper methods are accessible inside the view. Is this possible?

(I know it's not clean code, but this is a very particular low level service)

Aggregating Order Data - Ruby on Rails

Posted: 21 Nov 2016 08:06 AM PST

Looking for some advice on data aggregation for a Rails 5 API.

We've got a system which broken down into its simplest components has a Products model and an Orders model.

An Order has_many Products via a product_order join table.

We're generating spreadsheets of orders which contain a summary page with the orders ID, price and order notes and then one workbook per order which lists the individual products for that order.

We also need to output a summary page which contains an aggregated list of all of the Products and the quantity of each product ordered i.e.:

Product Summary Table  ---------------------  Name------|-Quantity  --------------------  Product 1 | 10  Product 2 | 20  

etc.

What's the best way to go about aggregating that data?

Thanks,

Mike

rails: access method of ApplicationController in initalizer

Posted: 21 Nov 2016 08:15 AM PST

I am trying to call the method current_user which is a method of ApplicaitonController inside of an initilizer, (specifically the initalizer for rails_admin:

  config.authorize_with do      user = current_user      redirect_to "/access_denied" if [!user.andand.is?("admin") || user.nil?].any?    end  

I get the error undefined local variable or methodcurrent_user' for # Did you mean? _current_user`

How can I access this method?

(rails) postgres error (column "posts.id" must appear in the GROUP BY clause)

Posted: 21 Nov 2016 07:45 AM PST

Welcome.....

I want to get the most user post on my rails app

@section.posts.select("posts.*, count(posts.user_id) as user_posts_count").group('posts.user_id')  .order("user_posts_count DESC").limit(10)  

But I have issue with postgreSQL while my code work without any issue on sqlit3 and mysql2

PG::GroupingError: ERROR: column "posts.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT posts.*, count(posts.user_id) as user_posts_count FR...

I need to use postgreSQL because it is the best for heroku but i don't know why I get this error on PostgreSQL

I hope if anyone help me >>>

Devise_token_auth Reset Password Flow 401 Error

Posted: 21 Nov 2016 06:47 AM PST

I'm trying to build a rails API and I'm using devise_token_auth gem for user authentication using tokens.

I managed to set everything up correctly and just bumped into a problem. Whenever I try to reset my password I get a 401 Unauthorized error from the API.

The flow is as follows:

  1. The user clicks the "Forgot my Password" button
  2. The user is redirected to a front-end app with a form to insert its' email
  3. The front-end app makes a POST request to the API 'auth/password' with the email and redirect_url params
  4. the API responds to this request by generating a reset_password_token and sending an email to the email address provided within the email parameter
  5. the user clicks the link in the email, which brings them to the 'Verify user by password reset token' endpoint (GET /password/edit)
  6. this endpoint verifies the user and redirects them to the redirect_url
  7. this redirect_url is a page on the frontend which contains a password and password_confirmation field
  8. the user submits the form on this frontend page, which sends a request to API: PUT /auth/password with the password and password_confirmation parameters
  9. the API changes the user's password and responds back with a success message

My problem occurs between step 8 and 9, where I get a 401 Unauthorized response. Why is that? What can I do to solve this issue?

Problems showing all Articles that have a certain Category in their list of categories?

Posted: 21 Nov 2016 07:55 AM PST

Problems showing all Articles that have a certain Category in their list of categories?

Articles  has_and_belongs_to_many Categories    Categories  has_and_belongs_to_many Articles    class CreateJoinTableArticleCategory < ActiveRecord::Migration    def change      create_join_table :articles, :categories do |t|        # t.index [:article_id, :category_id]        # t.index [:category_id, :article_id]      end    end  end  

Models and migrations are fine, seeding is fine info in rails console is fine but in the Controller I have problems showing all Articles for a certain category I get from the URL:

    class CategoriesController < ApplicationController          def show          @user = current_user          @categories = Category.all          @category = Category.friendly.find(params[:slug])          #@a = Article.where(category_id: @category, published: true)        #@a = Article.left_outer_joins(:categories).where("categories.category_id = @category")        #@a = Article.joins("LEFT JOIN articles_categories ON category.id = articles_categories.id")        #@a = Article.includes(:categories).where(@category)              @q = Question.where(category_id: @category, published: true)          @articles = (@q + @a).sort_by(&:created_at).reverse.paginate(page: params[:page], per_page: 4)        end        end  

How to set up Google Calendar API using Ruby client for server to server applications

Posted: 21 Nov 2016 06:45 AM PST

It took me a bit of reading in several locations, as well as looking in Stack Overflow to figure out how to use the Google API Ruby client with Google Calendar in a server to server application without giving the server client full access to all users. I just wanted it to have the ability to get/create/update/delete events for a single calendar. There may be other ways to do this, but I'm documenting below how I did it as it may help someone else out.

Access deep nested objects in Rails

Posted: 21 Nov 2016 06:36 AM PST

In my Rails app I have Users, Roles, and Permissions.

The associations are as follows:

class User < ActiveRecord::Base    has_and_belongs_to_many :roles, :join_table => 'users_roles'  end    class Role < ActiveRecord::Base    has_and_belongs_to_many :users, :join_table => 'users_roles'    has_and_belongs_to_many :permissions, :join_table => 'roles_permissions'  end    class Permission < ActiveRecord::Base    has_and_belongs_to_many :roles, :join_table => 'roles_permissions'  end  

When listing permissions I want to get the count of roles and users for that permission.

I can do:

<% @permissions.each do |permission| %>      <%= permission.roles.count %>  <% end %>  

But if I do:

<% @permissions.each do |permission| %>      <%= permission.roles.users.count %>  <% end %>  

I get an error that users is undefined!

In my controller I have:

@permissions = Permission.includes(roles: :users)  

So should be pulling through the users as well...

How to group records and then select distinct records based on column

Posted: 21 Nov 2016 08:24 AM PST

I am trying to group some records by category and then select all distinct/unique records based on alias column. Here is as far as i got but its not working - it still brings non distinct records.

Location.where("calendar_account_id = ?", current_user.calendar_accounts.first).group(:id,:alias).order("alias ASC").distinct.group_by(&:category)  

What am I doing wrong here?

Cucumber Test - Can anyone solve my 'edit' Scenario?

Posted: 21 Nov 2016 06:13 AM PST

I'm new to cucumber testing and I am confused as to why this will not work. As you can see I am trying to test that the updated details of a location are shown after edit but I recieve the below error. Can anyone help me spot what is wrong?

error =

Then I should see the updated location details # features/step_definitions/location_steps.rb:71    expected to find text "#<Location:0x007fac52ca98f0>" in "/Location/289" (RSpec::Expectations::ExpectationNotMetError)    ./features/step_definitions/location_steps.rb:73:in `/^I\ should\ see\ the\ updated\ location\ details$/'    features/location.feature:24:in `Then I should see the updated location details'  

feature.rb =

Scenario: editing a location   Given There is a location   And I am on the location details page   When I click on edit   Then I should see edit location form   When I edit location details   And I click submit changes   Then I should see the updated location details  

steps.rb =

Given "There is a location" do    @location = create(:location)  end    And "I am on the locations page" do    visit locations_path  end    When "I click on edit" do    click_link "edit"  end    Then "I should see edit location form" do    visit edit_location_path(@location)  end    When "I edit location details" do     @edited_location = build(:location)  end     And "I click submit changes" do     click_on "Submit Changes"   end     Then "I should see the updated location details" do     visit location_path(@location)     expect(location_path(@location)).to have_content(@edited_location)   end  

Errors while creating object using simple form

Posted: 21 Nov 2016 06:10 AM PST

i'm creating comments to post using simple form. It looks like this:

views/posts/show.html.slim

# ...    - if user_signed_in?    .row      .columns        h2 Add a comment:      .row      .medium-5.columns        = simple_form_for [post, comment] do |f|          = f.error_notification            .form-inputs            = f.input :body            .form-actions            = f.button :submit  

Also I have a validation in comments model:

validates :body, presence: true  

When I try to create empty comment I need to get errors under the fields. Here is should be 'can't be blank' under the body comment field

Here is my comments controller (I'm using responders and decent_exposure)

comments_controller.rb

class CommentsController < ApplicationController    before_action :authenticate_user!, only: :create    before_action :authorize_user!, only: :destroy      expose :post    expose_decorated :comment      def create      comment.post = post      comment.user = current_user      if comment.save        respond_with comment, location: post      else        # I should to write here something but I don't know what      end    end      def destroy      comment.destroy      respond_with comment, location: post    end      private      def authorize_user!      authorize(comment, :manage?)    end      def comment_params      params.require(:comment).permit(:body, :post_id)    end  end  

I dont know should I check comment.save like this or not? If yes, what should I write to else?

What is the difference between marked_for_detroy and destroy associated record in ActiveRecord?

Posted: 21 Nov 2016 07:04 AM PST

I understand that the autosave options has to be true and it happens when the parent is save. Is there any other differences? If the autosave is false, the associated record is left and only the link is removed?

Counter cache returns 1 unless reloaded

Posted: 21 Nov 2016 06:04 AM PST

I'm having an issue where I render my Comment model, and they all return with having 1 vote. It can either be 0 or 1 (I'm using 1 user to upvote). What I see is if that I reload the comment in the view it works correctly, if not it returns 1. I'm curious as to why this happens and how to fix this. I think it might be because I use a closure tree to get them, but I don't see any reason why it should impact it. Maybe someone can shed some light.

 def show      @resource = Resource.includes(:user).find(params[:id])      @comments = @resource.comments.includes(:children, :user)    end  

view:

<ul id="comments">    <%= comments_tree_for @comments %>  </ul>  

helper:

 module CommentsHelper    def comments_tree_for(comments)      comments.map do |comment|        render(comment) +        if comment.children.size > 0          content_tag(:div, comments_tree_for(comment.children), class: 'replies')        else          nil        end      end.join.html_safe    end  end  

partial:

  <% if current_user.voted?(comment) %>      <%= form_for comment.votes.find_by(voteable: comment), url: unvote_comment_path(comment), html: { method: :delete } do |f| %>        <%= f.submit "&#9660; #{comment.votes.size}".html_safe %>      <% end %>    <% else %>      <%= form_for comment.votes.build, url: upvote_comment_path(comment) do |f| %>        <%= f.submit "&#9650; #{comment.votes.size}".html_safe %>      <% end %>    <% end %>  

How to resolve error 504 Gateway Time-out in digitalocean rails

Posted: 21 Nov 2016 05:44 AM PST

Deploy rails app on digitalocean and after done all config changes and bundle installation when I run droplet url I get an error

504 Gateway Time-out   

/var/log/nginx/error.log

[error] 7825#0: *17 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 151.241.230.107, server: _, request: "POST / HTTP/1.1", upstream: "http://unix:/var/run/unicorn.sock/", host: "www.dynaforwardclassifiedsbooster.com"  

How to resolve it?

How can I make specific user(not current_user) sign out on rails-devise website?

Posted: 21 Nov 2016 06:12 AM PST

I want to know how I can make specific user(not current_user) sign out.

I saw this http://www.rubydoc.info/github/plataformatec/devise/master/Devise/Controllers/SignInOut#sign_out-instance_method and maked this code.

def kick_admin    user = User.find params[:user_id]    user.admin = false    user.save    sign_out user #want to kick him.   end  

But it does not make that user sign out but make me(current_user) signed out. What is the right way to use the sign_out method?

I checked this answer(Sign out specific user with Devise in Rails) but it was not helpful.

Angular ng-token-auth with Rails devise-token-auth, submitRegistration promise not resolving

Posted: 21 Nov 2016 05:20 AM PST

I am using ng-token-auth with Angular and devise-token-auth on Rails. I have successfully managed to create users in the database using the Registration form however the submitRegistration promise doesn't resolve even though the callbacks from Rails are successful.

Here is my Angular Controller submitRegistration function:

  $scope.handleRegBtnClick = function() {      $auth.submitRegistration($scope.registrationForm)      .then(function() {        console.log('SUCCESS')      })      .catch(function(){        console.log('FAILED')      })    };  

Here is the terminal callbacks from Rails when I submit a registration form:

Started POST "/auth" for ::1 at 2016-11-21 13:19:06 +0000  Processing by DeviseTokenAuth::RegistrationsController#create as HTML    Parameters: {"email"=>"hello@hello.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "confirm_success_url"=>"http://localhost:8080/#/", "config_name"=>"default", "registration"=>{"email"=>"hello@hello.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "confirm_success_url"=>"http://localhost:8080/#/", "config_name"=>"default"}}  Can't verify CSRF token authenticity.  Unpermitted parameters: confirm_success_url, config_name, registration  Unpermitted parameters: confirm_success_url, config_name, registration  Unpermitted parameters: confirm_success_url, config_name, registration     (0.3ms)  BEGIN     (1.5ms)  SELECT COUNT(*) FROM "users" WHERE "users"."provider" = $1 AND "users"."email" = $2  [["provider", "email"], ["email", "hello@hello.com"]]    SQL (1.2ms)  INSERT INTO "users" ("uid", "encrypted_password", "confirmed_at", "email", "tokens", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["uid", "hello@hello.com"], ["encrypted_password", "$2a$10$FJoe7FHrRLkLwpIJ7x1tMOeACdawRNwdDKhbLA.BE/Xyd698URW5i"], ["confirmed_at", 2016-11-21 13:19:06 UTC], ["email", "hello@hello.com"], ["tokens", "{}"], ["created_at", 2016-11-21 13:19:06 UTC], ["updated_at", 2016-11-21 13:19:06 UTC]]     (0.6ms)  COMMIT     (0.1ms)  BEGIN    SQL (0.5ms)  UPDATE "users" SET "uid" = $1, "confirmed_at" = $2, "tokens" = $3, "updated_at" = $4 WHERE "users"."id" = $5  [["uid", "a6cd0e44-de55-480c-adb0-f51e781923d0"], ["confirmed_at", 2016-11-21 13:19:06 UTC], ["tokens", "{\"7f2HNXfpnjr8WY9qdoyBdw\":{\"token\":\"$2a$10$n9Nr8OirL.aR41zWPIbjauF5b91qgjlwz7do2QG6Mn93FpLqKuZZO\",\"expiry\":1480943946}}"], ["updated_at", 2016-11-21 13:19:06 UTC], ["id", 19]]     (0.5ms)  COMMIT    User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 19], ["LIMIT", 1]]     (0.2ms)  BEGIN    SQL (0.5ms)  UPDATE "users" SET "uid" = $1, "confirmed_at" = $2, "updated_at" = $3 WHERE "users"."id" = $4  [["uid", "615cb6c4-2c54-4141-8280-e0223f20dd30"], ["confirmed_at", 2016-11-21 13:19:06 UTC], ["updated_at", 2016-11-21 13:19:06 UTC], ["id", 19]]     (0.5ms)  COMMIT  Completed 200 OK in 250ms (Views: 1.2ms | ActiveRecord: 6.5ms)  

The registration completes successfully on the Rails server however the promise from Angular never resolves.

Please note the login and logout promises successfully resolve.

Could not find json-1.8.2 in any of the sources (Bundler::GemNotFound)

Posted: 21 Nov 2016 05:15 AM PST

I deploy my app on digitalocean and doen all configuration chagnes. When I access its url it gives an error

504 Gateway Time-out  

Error in unicorn.log is

E, [2016-11-21T07:58:42.365353 #3882] ERROR -- : Could not find json-1.8.2 in any of the sources (Bundler::GemNotFound)  /usr/local/rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/spec_set.rb:92:in `block in materialize'  /usr/local/rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/spec_set.rb:85:in `map!'  /usr/local/rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/spec_set.rb:85:in `materialize'  /usr/local/rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/definition.rb:132:in `specs'  /usr/local/rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/definition.rb:177:in `specs_for'  /usr/local/rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/definition.rb:166:in `requested_specs'  /usr/local/rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/environment.rb:18:in `requested_specs'  /usr/local/rvm/gems/ruby-2.2.1@global/gems/bundler-1.8.4/lib/bundler/runtime.rb:13:in `setup'  

Error in nginx is

*17 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 151.241.230.107, server: _, request: "POST / HTTP/1.1", upstream: "http://unix:/var/run/unicorn.sock/", host: "www.dynaforwardclassifiedsbooster.com"  

How do I alias a rails route with an id?

Posted: 21 Nov 2016 05:38 AM PST

I have these routes:

get '/welcome', to: redirect('/welcome/1')  get 'welcome/:id' => 'users#welcome'  

The redirect route does a 301 to /welcome/1.

Instead of doing a redirect I'd like it to just execute users#welcome with an id of 1.

How do I do this?

reload rails form without changing current parameters

Posted: 21 Nov 2016 04:32 AM PST

can someone help me with this issue, I want to refresh page where rails form present with params filled in it, so when someone checked checkbox that page should be reload without changing values present in the form. Thanks in advance.

Rails with ReactJS - realtime data fetch

Posted: 21 Nov 2016 06:29 AM PST

Can I fetch the data from the my database in realtime using Rails and ReactJS?

I have just started using React with Rails as this is pretty awesome combination. What I want to know is if there is a way to tell the view to update itself after a component is deleted/ created (so a record is removed/ added to the database)? Something like user after entering the page will subscribe to the database event (?).

What I have now is ComponentContainer with a custom fetch method that gets json from the server. I put it in the componentWillMount and inside a setInterval and run it every single second:

var ComponentsContainer = React.createClass({      componentWillMount() {          this.fetchRecords();          setInterval(this.fetchRecords, 1000);      },      fetchRecords() {          $.getJSON(path_to_results,              (data) => this.setState({components: data});      }, ...render methods etc.  });  

I am trying to use selenium in Capybara to locally test the rails app. I am using rake to start the task, but it gives following error

Posted: 21 Nov 2016 04:26 AM PST

unable to connect to Mozilla geckodriver 127.0.0.1:4444 (Selenium::WebDriver::Error::WebDriverError)

Conversion of a javascript object to a ruby hash

Posted: 21 Nov 2016 04:35 AM PST

In my existing ruby on rails application, I have a JavaScript object (hash) in one of my view file. The hash needs to be submitted back to the controller during form submission. I have converted the hash to JSON using JSON.stringify(hash_name) method. But it produces a string and I can get the string which looks like the hash in my controller. My purpose was not that. I need to dereference the hash in controller , so that I can save the dereferenced values into database.

My hash looks like as following when I am printing it in controller:

{"Bearing":[["Jeekay",0],["Ecodrive",0]],"Civil":[["Nirlon",0],["SKF",0]],"Compressor":[["Jeekay",0],["Ecodrive",0],["SKF",0]]}   

And it should be like it but not the string.

I have a hidden field in my view. I am putting the hash to the value of the hidden field and submitting the form as

$("#javascript_data").val(JSON.stringify(ultimate_hash));  

In my controller I am getting the data as:

check_data=params[:javascript_data]  

But check_data is a string.

But since its a string,my purpose was not solved. Please help me by giving some suggestions about how to pass the JavaScript hash to the controller as it is.

Thanks in advance!

Creating dynamic workflow forms in Angular 2

Posted: 21 Nov 2016 04:34 AM PST

I am currently working on an Angular 2 application with a RoR backend. The application currently generates notifications that all belong to a certain notificationType. Each notificationType has a conditional form that roughly looks as follows:

  • Did you contact user X?
  • If yes: Did you do step Y? If no: Did you do step Z?
  • ... more questions ...

I am wondering what would be a good approach to model this. I have about 15 notificationTypes (and this will probably grow in the future) and therefor don't feel like writing a specific view for each notificationType. I found a package called ng2-formly that automatically generates forms based on a JavaScript object. An approach would be to store a JavaScript object that defines a certain form in the database with the related notificationType.

I was wondering if people have experience with certain tasks in Angular 2 and if they think that I am looking in the good direction.

APIConnectionError with Stripe API

Posted: 21 Nov 2016 04:38 AM PST

I am trying to integrate the Stripe API in my Rails project. But I am wondering why I have a failed APIConnectionError when I have checked that my internet connection is fine.

In users_controller.rb:

def charge    token = params["stripeToken"]    customer = Stripe::Customer.create(      source: token,      plan: 'mysubscriptionlevel1',      email: current_user.email    )      current_user.subscription.stripe_user_id = customer.id    current_user.subscription.active = true    current_user.subscription.save      redirect_to users_info_path  end  

In the /views/users/_form.html.erb, I have the form POST-ing to the /users/charge url path.

  <h4>Begin your £9.99 a month subscription</h4>    <form action="/users/charge" method="POST" id="payment-form">      <span class="payment-errors"></span>  

And in my routes.rb file, I have:

post '/users/charge', to: 'users#charge'  

In config/initializer/stripe.rb, I have required stripe and put my api key in the .env file.

require "stripe"  Stripe.api_key = ENV["STRIPE_API_KEY"]  

I have also included the stripe gem in my Gemfile:

gem 'stripe', :git => 'https://github.com/stripe/stripe-ruby'  gem 'dotenv-rails', :groups => [:development, :test]  

I am not sure what I am missing and this is the error that I get when I call the charge action in users_controller.rb:

Stripe::APIConnectionError (Unexpected error communicating when trying to connect to Stripe. You may be seeing this message because your DNS is not working. To check, try running 'host stripe.com' from the command line.    (Network error: Failed to open TCP connection to : (getaddrinfo: nodename nor servname provided, or not known))):  

What does it mean by the DNS not working and how can I debug by just running 'host stripe.com'

Check for duplicate record and then create

Posted: 21 Nov 2016 05:48 AM PST

I have an rails app wherein am trying to either downvote or upvote an contact. I have a user model powered by devise. I have an feedback model too in place which stores which user has upvoted/downvoted an contact. How do I get to insert record into the feedback table when two users are trying to upvote/downvote the same contact details?

Run rails project on windows 7 VM

Posted: 21 Nov 2016 04:18 AM PST

I have dual operating system on my machine windows and ubuntu.

I want to run the server on ubuntu like this: rails s -b 0.0.0.0. And browse the application on windows os by using my_machines_ip:3000.

Is it possible?

No comments:

Post a Comment