Sunday, December 18, 2016

Rails dropdown menu - assign parameter for path from the user's selection | Fixed issues

Rails dropdown menu - assign parameter for path from the user's selection | Fixed issues


Rails dropdown menu - assign parameter for path from the user's selection

Posted: 18 Dec 2016 08:12 AM PST

I want this form to appear as a dropdown list:

<%= form_tag job_index_path do %>    <%= select_tag "area", options_for_select(@areas.collect { |area| [ area.name, area.name ] }), :onchange => "this.form.submit();" %>  <% end %>  

The desired outcome is that when the form is submitted it will take the 'area' that the user select and add it as a params[:area] option for the following route:

get ':area' => 'job#index', :as => 'job_index'  

For example, if the list that has three options: London, Dublin, Paris. When the user selects 'Dublin', the form submits and assigns params[:area] to be 'Dublin'. It then goes to the URL localhost:3000/Dublin.

However, I can't figure out how to add the :area parameter to the form path once the user makes their suggestion. I'm sure its probably a very easy thing to do, but I can't seem to figure it out.

Any help is greatly appreciated :)

How to change the default routing of a model at root in rails?

Posted: 18 Dec 2016 08:07 AM PST

I am trying to change the controller and action of users model in routing.rb when pointed at /users url. Here is how I tried to change it:

resources :users, only: :show do      get 'favorites' => 'routers#client'      get 'tours' => 'routers#client'      get 'offers' => 'routers#client'      get 'open_houses' => 'routers#client'      get 'searches'  end  get 'users/:id' => 'routers#client'  

The favorties, tours, offers and open_houses route to routers_controller client action when url such as /users/:id/favorites etc are called. But when calling the /user/:id, it doesn't map to routers controller. How should I change the index route to this controller?

Failed to push to Heroku: fails on Ruby version

Posted: 18 Dec 2016 08:10 AM PST

When I push to Heroku I get the following error:

remote: Building source:  remote:   remote: -----> Ruby app detected  remote: -----> Compiling Ruby/Rails  remote:        Your app was upgraded to bundler 1.13.6.  remote:        Previously you had a successful deploy with bundler 1.11.2.  remote:          remote:        If you see problems related to the bundler version please refer to:  remote:        https://devcenter.heroku.com/articles/bundler-version  remote: -----> Using Ruby version: ruby-2.3.0  remote: -----> Installing dependencies using bundler 1.13.6  remote:        Ruby version change detected. Clearing bundler cache.  remote:        Old: ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]  remote:        New: ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]  remote:        Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment  remote:        Your Ruby version is 2.3.0, but your Gemfile specified 2.3.1  remote:        Bundler Output: Your Ruby version is 2.3.0, but your Gemfile specified 2.3.1  remote:  !  remote:  !     Failed to install gems via Bundler.  remote:  !  remote:  !     Push rejected, failed to compile Ruby app.  remote:   remote:  !     Push failed  

It works locally. Locally, ruby -v returns ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux].

How to solve this issue? Is Heroku not yet accepting Ruby 2.3.1? I could of course switch back locally to version 2.3.0 but I would expect this not to be necessary?

Error with routing and headers in Ruby on Rails

Posted: 18 Dec 2016 07:52 AM PST

I'm with the following problem:

I'm trying to create a route with a default format type as JSON:

Rails.application.routes.draw do    namespace :api, path: '/', constraints: { subdomain: 'api' } do      namespace :v1 do        resources :pessoas_fisicas, defaults: { format: 'json' }      end    end  end  

When I access the URL http://api.sistema-controle-contas.com:3000/v1/pessoas_fisicas, it shows the expected result, a JSON output.

The controller that I'm using for this code is:

 def index      @pessoas_fisicas = PessoaFisica.all        respond_to do |format|        format.json { render json: @pessoas_fisicas, status: 200 }        format.xml { render xml: @pessoas_fisicas, status: 200 }      end   end  

But It always return a JSON file, even if I send a header asking for a XML like this:

$ curl -IH 'Accept: application/xml' 'http://api.sistema-controle-contas.com:3000/v1/pessoas_fisicas'  

It returns:

HTTP/1.1 200 OK X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff Content-Type: application/json; charset=utf-8

If I took off the 'defaults: { format: 'json' }' from the route, the curl request return the XML expected. However, the application stops to work as it does not know the format that is needed to show.

And on the Browser I got:

"status": 406,  "error": "Not Acceptable",  "exception": "#<ActionController::UnknownFormat: ActionController::UnknownFormat>"  

Could someone help with this, please?

Adding a link in the body of mail_to - Rails 5

Posted: 18 Dec 2016 07:05 AM PST

I am unsure how to add a link to the body of mail_to.

i would like to make @social.title (BGF Ventures: the truth about fundraising) a link, so when clicked the user is directed to the page of the event/social.

Is this possible? if so, could one advise me how

i have the below code:

<span>  <%= mail_to '', '', class: "fa fa-envelope",                     subject: "#{@social.title}",                     body: "Hi, would like to invite you to the social '#{@social.title}'" %>  </span>  

enter image description here

Image_tag and turbolink

Posted: 18 Dec 2016 06:15 AM PST

I started my journey with Rails and Ruby a couple of days ago and so far it is going well and I'm loving it!

Though, I do have a minor concern that I cannot find a solution to. I've had a minor sneak peek on turbolink and how that is embedded with Rails. But, my question (problem?) is that whenever I import/include an image (which is located in app/assets/image) with Rails image_tag(...), that image is reloaded whenever I redirect to another page. But if I use <img src="..." whereas the src is an extern link (image fetched from another page) it is not being re-fetched (meaning, it's cached when I redirect to another page).

So my question is: is there a special way to apply turbolink to image_tag?

Thanks.

Action Cable on HTTPS error during WebSocket handshake: Unexpected response code: 404

Posted: 18 Dec 2016 05:25 AM PST

It works fine with http, but when upgrade to https this error happen.

Here is my environments:

  • AWS Elastic Beanstalk
  • 64bit Amazon Linux 2016.09 v2.2.0 running Ruby 2.3 (Puma)
  • ActionCable

Configurations:

    location /cable {              proxy_pass http://my_app;              proxy_http_version 1.1;              proxy_set_header Upgrade $http_upgrade;              proxy_set_header Connection "Upgrade";              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;              proxy_set_header Host $http_host;              proxy_set_header X-Real-IP $remote_addr;              proxy_set_header X-Forwarded-Proto https;            }  

Log from server:

    [2016-12-18T13:07:48.252727 #19764]  INFO -- : [4d1c9c93-2724-48c6-8b7c-4e42beae94c7] Started GET "/cable" for 162.158.166.199 at 2016-12-18 13:07:48 +0000          [2016-12-18T13:07:48.254025 #19764]  INFO -- : [4d1c9c93-2724-48c6-8b7c-4e42beae94c7] Started GET "/cable/"[non-WebSocket] for 162.158.166.199 at 2016-12-18 13:07:48 +0000      [2016-12-18T13:07:48.254084 #19764] ERROR -- : [4d1c9c93-2724-48c6-8b7c-4e42beae94c7] Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: )      [2016-12-18T13:07:48.254146 #19764]  INFO -- : [4d1c9c93-2724-48c6-8b7c-4e42beae94c7] Finished "/cable/"[non-WebSocket] for 162.158.166.199 at 2016-12-18 13:07:48 +0000  

I really appreciate your help.

Thanks.

What is the proper way to make an increment function work?

Posted: 18 Dec 2016 04:57 AM PST

I'm creating a website that let people read short stories in several chapters. For this, I nested a chapter scaffold inside a novel scaffold, and linked (novel has_many :chapters, chapters belongs_to :novel) them both together. However I'm trying to get the chapter's number inside the URL (instead of the id, which never decreases). Setting the chapter as is is not a problem, but I'd like to automate the chapter number without my users needing to add it themselves.

To do so, I figured that all I needed was to get how many chapter the current novel had by checking self.class.where(:novel_id => @novel).count. At this point, I have no issues, however it gets complicated when I try to increment this number, I get the error: undefined method 'anoter_one' for 0:Fixnum

Here is my "another_one" function inside my model (I tried some things)

  def another_one      @number = self.class.where(:novel => @novel).count.to_i      @number.increment    end  

Here is the controller

  def create      @novel = Novel.find(params[:novel_id])      @chapter = Chapter.new(chapter_params)      @chapter.chapter_number.another_one      @chapter.novel = @novel      if @chapter.save        redirect_to novel_chapter_path(@novel, @chapter), notice: 'Chapter was successfully created.'      else        render :new      end    end  

What am I doing wrong ?

Thank you in advance

I want some reference on designing for rails app [on hold]

Posted: 18 Dec 2016 03:35 AM PST

Its more than 3 months i have been learning ruby on rails. Now I've been starting to build some blogs but the thing that's coming on my way is the designing of my blogs. I am having some serious problem in html/css files or say (html.erb)! Any reference tutorials for learning designing in rails 5?

Configuring strong parameters for dynamic keys

Posted: 18 Dec 2016 03:50 AM PST

I'm attempting to provide a form that allows an admin to edit all values of a particular model Submission, almost as though it was a spreadsheet. Submission is comprised of one string field :domain.

The problem is that I can't figure out how to deal with strong params within this context. I've found similar examples of dealing with dynamic keys like this one but I can't quite figure out how to apply them to my parameter structure. I think I'm just not clear enough on how tap works.

Here's an example of my parameters:

{"3"=>{"domain"=>"domain3"}, "2"=>{"domain"=>"domain2"}, "1"=>{"domain"=>"domain1"}  

In case it helps, here's the form I'm using:

<%= form_tag update_multiple_submissions_path, method: :put do %>      <table data-toggle="table" data-sort-name = "domain" data-sort-order = "desc">          <thead>              <th data-field="domain" data-sortable="true">Domain</th>          </thead>          <tbody>              <% @submissions.each do |submission| %>                  <%= simple_fields_for "submissions[]", submission, defaults: {label: false} do |f| %>                      <tr>                          <td><%= submission.domain %><%= f.input :domain %></td>                      </tr>                  <% end %>              <% end %>          </tbody>      <table>      <%= submit_tag "Save" %>  <% end %>  

And in case you're curious, here's the update_multiple method from my controller. If this looks familiar, I got the outline from a railscast, which was very effective in rails3 before strong params was (were?) ubiquitous.

  def update_multiple      logger.debug "update_multiple #{submission_params}"      @submissions = Submission.update(submission_params[:submissions].keys, params[:submissions].values)        flash[:notice] = "Updated Submissions"        redirect_to review_submissions_path    end  

This works very well if I bypass strong prams altogether using params.permit! but, of course, this is an unacceptable solution.

Thanks for any help!

"Expected string default value for `--jbuilder`; got true (boolean)" error in a new rails project

Posted: 18 Dec 2016 05:48 AM PST

I am starting a new project, and have done this meany times now. However, this is the first time I have run into this issue!

I created the app as normal rails new myapp -d postgresql

I've created the DB using rails db:create and ran the site rails s. It all works, and I see the Rails welcome/holding page.

Now I start to create my models, rails g model user for example. And I get this!

Expected string default value for `--jbuilder`; got true (boolean)        invoke  active_record    The name 'User' is either already used in your application or reserved by Ruby on   Rails. Please choose an alternative and run this generator again.  

Ok that's fair enough, I understand the error message. So I thought I would try to create a different model. When I run rails g model testing, and I get...

Running via Spring preloader in process 31815  Expected string default value for '--jbuilder'; got true (boolean)        invoke  active_record        create    db/migrate/20161217171019_create_testings.rb        create    app/models/testing.rb        invoke    test_unit        create      test/models/testing_test.rb        create      test/fixtures/testings.yml  

Has anyone else had this issue and if so any ideas why? I have tried running bundle install and bundle update with no luck. I have also tried setting the thor version as mentioned in this post

I am using Rails 5.0.0.1 and Ruby 2.3.1. I noticed this has only just started happening since I did an update to macOS to 10.12.1 I am not sure if they are related.

Update

So I started to test this out. And I created a couple of different projects 'rails new testapppg' and 'rails new testapp-pg'.

On both of apps I changed the thor gem gem 'thor', '0.19.1'. I then went on to run bundle update, and create the DB. Now both of these projects created the test models when running rails g model sample

Cool! So that is the fix. So I went back and recreated my pxl-insight app, updated the thor gem, created the DB. Now when I went to create the model I get the errors again!?

So my next question is does Rails cache project names? which is why the new projects worked fine, but the one with the previously used name causes the error?

SECRET_KEY_BASE config vars set too late - Can't start Rails app on Heroku

Posted: 18 Dec 2016 03:05 AM PST

RuntimeError, missing secret_key_base when starting a Rails app on Heroku. I've already added the secret as a ENV var and looking at the logs it feels that Heroku is setting it up too late.
Has something similar happened to you? How would you recommend approaching this?

2016-12-18T01:57:34.469373+00:00 app[web.1]: #<RuntimeError: Missing `secret_key_base` for 'production' environment, set this value in `config/secrets.yml`>  2016-12-18T01:57:34.469375+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:513:in `validate_secret_key_config!'  2016-12-18T01:57:34.469376+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:246:in `env_config'  2016-12-18T01:57:34.469377+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/application.rb:521:in `build_request'  2016-12-18T01:57:34.469377+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:693:in `build_request'  2016-12-18T01:57:34.469378+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/railties-5.0.0.1/lib/rails/engine.rb:521:in `call'  2016-12-18T01:57:34.469379+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/puma-3.6.2/lib/puma/configuration.rb:225:in `call'  2016-12-18T01:57:34.469379+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/puma-3.6.2/lib/puma/server.rb:578:in `handle_request'  2016-12-18T01:57:34.469380+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/puma-3.6.2/lib/puma/server.rb:415:in `process_client'  2016-12-18T01:57:34.469381+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/puma-3.6.2/lib/puma/server.rb:275:in `block in run'  2016-12-18T01:57:34.469381+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/puma-3.6.2/lib/puma/thread_pool.rb:116:in `call'  2016-12-18T01:57:34.469382+00:00 app[web.1]: /app/vendor/bundle/ruby/2.2.0/gems/puma-3.6.2/lib/puma/thread_pool.rb:116:in `block in spawn_thread'  2016-12-18T02:32:44.013101+00:00 heroku[web.1]: Stopping all processes with SIGTERM  2016-12-18T02:32:43.362607+00:00 heroku[web.1]: Idling  2016-12-18T02:32:43.362607+00:00 heroku[web.1]: State changed from up to down  2016-12-18T02:32:44.038208+00:00 app[web.1]: - Gracefully stopping, waiting for requests to finish  2016-12-18T02:32:44.038778+00:00 app[web.1]: - Goodbye!  2016-12-18T02:32:44.038774+00:00 app[web.1]: === puma shutdown: 2016-12-18 02:32:44 +0000 ===  2016-12-18T02:32:44.039352+00:00 app[web.1]: Exiting  2016-12-18T02:32:44.259020+00:00 heroku[web.1]: Process exited with status 0  2016-12-18T09:45:45.086929+00:00 heroku[web.1]: State changed from down to starting  2016-12-18T09:45:44.933284+00:00 app[api]: Set SECRET_KEY_BASE config vars by user XXX@gmail.com  2016-12-18T09:45:44.933284+00:00 app[api]: Release v12 created by user XXX@gmail.com  

Using Ransack in rails for searching companies and associated categories

Posted: 18 Dec 2016 12:17 AM PST

I have a search feature in my app where I search for a company and the results are companies fitting the name and the associated primary_categories for all of those companies.

I'm using ransack to grab the relevant companies.

Companies and PrimaryCategories have a has_many_and_belongs_to_many association. I'm refactoring the code to grab relevant primary categories from returned companies.

Below is the method before the changes.

def search    @q = Company.ransack(name_cont: params[:q][:name], keywords_name_cont: params[:q][:name], m: 'or')    @companies = @q.result.uniq    @q2 = PrimaryCategory.ransack(name_cont: params[:q][:name])    @categories = @q2.result.uniq    @search_term = params[:q][:name]  end  

On the search results page, I can retrieve the company but the primary categories are blank since I'm being returned an empty array object.

I'm looking for a clean way to extract the associated primary_categories from the returned companies

I've re-written the above method to include an array object.

def search    @q = Company.ransack(name_cont: params[:q][:name], keywords_name_cont: params[:q][:name], m: 'or')    @companies = @q.result.uniq    @categories = []    @search_categories = @companies.each {|co| @categories << co.primary_categories}    @categories.flatten!.uniq    @search_term = params[:q][:name]  end  

This works but I want to know if I can get the same result using ransack. Is there a more efficient way to grab the associated objects using ransack instead of creating a separate categories array?

NameError uninitialized constant Model::Object

Posted: 18 Dec 2016 07:23 AM PST

I'm new to ruby on rails. Ihe error I have is

NameError in ReviewsController#create  uninitialized constant User::Review  Extracted source:      @review = current_user.reviews.build(review_params)  

I read on other stack overflow questions that usually the error for wrong names or forgetting belongs_to or has_many but I believe I've set the relations correctly. I am using the gem devise to handle the user and sign in/sign up etc

Reviews.rb

class Reviews < ActiveRecord::Base      belongs_to :user      belongs_to :renters    end  

User.rb

class User < ActiveRecord::Base    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable      has_many :reviews  end  

Reviews_Controller.rb

class ReviewsController < ApplicationController    before_action :set_renter    before_action :authenticate_user!      def new      @review = Reviews.new(renters: @renter)    end      def create      @review = current_user.reviews.build(review_params)      @review.renter = @renter      @review.save       redirect_to @renter     end      private      def set_renter        @renter = Renters.find(params[:renter_id])      end        def review_params        params.require(:reviews).permit(:comment, :rating)      end  end  

The Renters model is working fine and similar code I have to make a new Renter is working so I am not sure what is wrong.

Rails 3: how to check if very large migration is running properly

Posted: 18 Dec 2016 03:04 AM PST

I want to update all of a column in a table with over 2.2 million rows where the attribute is set to null. There is a Users table and a Posts table. Even though there is a column for num_posts in User, only about 70,000 users have that number populated; otherwise I have to query the db like so:

@num_posts = @user.posts.count  

I need to use a migration to update the attributes and I'm not sure whether or not it's running properly. Here is my migration file:

class UpdateNilPostCountInUsers < ActiveRecord::Migration    def up      nil_count = User.select(:id).where("num_posts IS NULL")        nil_count.each do |user|        user.update_attribute :num_posts, user.posts.count      end    end      def down    end  end  

In my console, I ran a query on the first 10 rows where num_posts was null, and then used puts for each user.posts.count . The total time was 85.3ms for 10 rows, for an avg of 8.53ms. 8.53ms*2.2million rows is about 5.25 hours, and that's without updating any attributes.

How do I know if my migration is running as expected? Is there a way to log to the console %complete? I really don't want to wait 5+ hours to find out it didn't do anything. Much appreciated.

Rails app deploy to heroku with error H10

Posted: 17 Dec 2016 11:56 PM PST

I'm deploying a Rails (Rails v5.0.0.1) app to heroku. However when I try visiting the app it crashes with error code of H10. After googling for a while I tried restarting all dynos for the app as people suggest but it didn't work. What's even weirder is that I cannot run heroku run rails console to access the console, when I run that, it shows:

Usage:    rails new APP_PATH [options]    Options:    -r, [--ruby=PATH]                                      # Path to the Ruby binary of your choice                                                           # Default: /app/vendor/ruby-2.3.0/bin/ruby    -m, [--template=TEMPLATE]                              # Path to some application template (can be a filesystem path or URL)    -d, [--database=DATABASE]                              # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)                                                           # Default: sqlite3    -j, [--javascript=JAVASCRIPT]                          # Preconfigure for selected JavaScript library                                                           # Default: jquery        [--skip-gemfile], [--no-skip-gemfile]              # Don't create a Gemfile    -B, [--skip-bundle], [--no-skip-bundle]                # Don't run bundle install    -G, [--skip-git], [--no-skip-git]                      # Skip .gitignore file        [--skip-keeps], [--no-skip-keeps]                  # Skip source control .keep files    -M, [--skip-action-mailer], [--no-skip-action-mailer]  # Skip Action Mailer files    -O, [--skip-active-record], [--no-skip-active-record]  # Skip Active Record files...  

Note that I can run heroku run rake db:migrate after pushing to heroku. Here's the logs:

2016-12-18T06:44:34.515479+00:00 heroku[web.1]: Process exited with status 127  2016-12-18T06:44:46.337848+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mighty-island-98480.herokuapp.com request_id=fd929087-20a6-4c20-b534-f14261d3de11 fwd="210.245.33.22" dyno= connect= service= status=503 bytes=  2016-12-18T06:44:46.757726+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=mighty-island-98480.herokuapp.com request_id=ff3d39de-e593-41d4-b8d1-26fa9befc27e fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  2016-12-18T06:46:59.953430+00:00 heroku[web.1]: State changed from crashed to starting  2016-12-18T06:47:05.203056+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 26350 -e production`  2016-12-18T06:47:06.697360+00:00 app[web.1]: bash: bin/rails: No such file or directory  2016-12-18T06:47:06.797834+00:00 heroku[web.1]: State changed from starting to crashed  2016-12-18T06:47:06.798798+00:00 heroku[web.1]: State changed from crashed to starting  2016-12-18T06:47:06.775021+00:00 heroku[web.1]: Process exited with status 127  2016-12-18T06:47:11.275436+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 31405 -e production`  2016-12-18T06:47:13.273106+00:00 app[web.1]: bash: bin/rails: No such file or directory  2016-12-18T06:47:13.382651+00:00 heroku[web.1]: State changed from starting to crashed  2016-12-18T06:47:13.364125+00:00 heroku[web.1]: Process exited with status 127  2016-12-18T06:47:15.177482+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=mighty-island-98480.herokuapp.com request_id=838f042a-36fb-4b80-9dd1-68146388a2f9 fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  2016-12-18T06:47:14.847769+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mighty-island-98480.herokuapp.com request_id=329ddb98-3588-4a7e-ba85-86f2ebb0c787 fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  2016-12-18T06:47:17.892965+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mighty-island-98480.herokuapp.com request_id=64f4d85b-f4be-473b-886b-16bcbabcebb2 fwd="210.245.33.22" dyno= connect= service= status=503 bytes=  2016-12-18T06:47:18.158159+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=mighty-island-98480.herokuapp.com request_id=6f95c551-e2a1-4afd-aa6a-00344743d3d9 fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  2016-12-18T06:47:35.998915+00:00 app[api]: Starting process with command `bundle exec rake rails console` by user yaphats280396@gmail.com  2016-12-18T06:47:42.534769+00:00 heroku[run.1014]: Awaiting client  2016-12-18T06:47:42.584498+00:00 heroku[run.1014]: Starting process with command `bundle exec rake rails console`  2016-12-18T06:47:42.560559+00:00 heroku[run.1014]: State changed from starting to up  2016-12-18T06:47:50.393316+00:00 heroku[run.1014]: Process exited with status 1  2016-12-18T06:47:50.411848+00:00 heroku[run.1014]: State changed from up to complete  2016-12-18T06:48:03.813169+00:00 app[api]: Starting process with command `rails console` by user yaphats280396@gmail.com  2016-12-18T06:48:09.475386+00:00 heroku[run.8367]: Awaiting client  2016-12-18T06:48:09.520745+00:00 heroku[run.8367]: Starting process with command `rails console`  2016-12-18T06:48:09.640673+00:00 heroku[run.8367]: State changed from starting to up  2016-12-18T06:48:14.736012+00:00 heroku[run.8367]: State changed from up to complete  2016-12-18T06:48:14.699247+00:00 heroku[run.8367]: Process exited with status 0  2016-12-18T06:52:47.096470+00:00 heroku[slug-compiler]: Slug compilation started  2016-12-18T06:55:24.601041+00:00 heroku[slug-compiler]: Slug compilation started  2016-12-18T06:58:02.189014+00:00 app[api]: Deploy 18728fe by user yaphats280396@gmail.com  2016-12-18T06:58:02.189014+00:00 app[api]: Release v6 created by user yaphats280396@gmail.com  2016-12-18T06:58:02.340404+00:00 heroku[slug-compiler]: Slug compilation started  2016-12-18T06:58:02.340411+00:00 heroku[slug-compiler]: Slug compilation finished  2016-12-18T06:58:02.437765+00:00 heroku[web.1]: State changed from crashed to starting  2016-12-18T06:58:07.513403+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 44886 -e production`  2016-12-18T06:58:09.081681+00:00 heroku[web.1]: Process exited with status 127  2016-12-18T06:58:08.964854+00:00 app[web.1]: bash: bin/rails: No such file or directory  2016-12-18T06:58:09.105664+00:00 heroku[web.1]: State changed from starting to crashed  2016-12-18T07:00:25.355827+00:00 heroku[web.1]: State changed from crashed to starting  2016-12-18T07:00:30.147971+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 52383 -e production`  2016-12-18T07:00:31.821352+00:00 app[web.1]: bash: bin/rails: No such file or directory  2016-12-18T07:00:31.890663+00:00 heroku[web.1]: State changed from starting to crashed  2016-12-18T07:00:31.872039+00:00 heroku[web.1]: Process exited with status 127  2016-12-18T07:01:45.326964+00:00 app[api]: Starting process with command `bundle exec rake db:migrate` by user yaphats280396@gmail.com  2016-12-18T07:01:50.459013+00:00 heroku[run.9961]: Awaiting client  2016-12-18T07:01:50.478532+00:00 heroku[run.9961]: Starting process with command `bundle exec rake db:migrate`  2016-12-18T07:01:50.751333+00:00 heroku[run.9961]: State changed from starting to up  2016-12-18T07:01:56.569373+00:00 heroku[run.9961]: Process exited with status 0  2016-12-18T07:01:56.582918+00:00 heroku[run.9961]: State changed from up to complete  2016-12-18T07:02:03.799642+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mighty-island-98480.herokuapp.com request_id=a886d9c7-771c-4bbc-b0ae-c69a9a2711eb fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  2016-12-18T07:02:04.128488+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=mighty-island-98480.herokuapp.com request_id=b639d3fe-89b8-4e85-bec5-092711ab9177 fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  2016-12-18T07:02:06.282079+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mighty-island-98480.herokuapp.com request_id=2a99589c-6000-464f-8d6e-15bca538bb84 fwd="210.245.33.22" dyno= connect= service= status=503 bytes=  2016-12-18T07:02:06.575156+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=mighty-island-98480.herokuapp.com request_id=b520a6ee-4bfa-4116-b535-ce00c641097c fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  2016-12-18T07:02:23.077596+00:00 app[api]: Starting process with command `rails console` by user yaphats280396@gmail.com  2016-12-18T07:02:29.656336+00:00 heroku[run.4122]: Awaiting client  2016-12-18T07:02:29.734024+00:00 heroku[run.4122]: Starting process with command `rails console`  2016-12-18T07:02:29.759224+00:00 heroku[run.4122]: State changed from starting to up  2016-12-18T07:02:35.660219+00:00 heroku[run.4122]: State changed from up to complete  2016-12-18T07:02:35.644039+00:00 heroku[run.4122]: Process exited with status 0  2016-12-18T07:06:57.871793+00:00 app[api]: Starting process with command `rails console` by user yaphats280396@gmail.com  2016-12-18T07:07:04.028124+00:00 heroku[run.5253]: State changed from starting to up  2016-12-18T07:07:04.151355+00:00 heroku[run.5253]: Awaiting client  2016-12-18T07:07:04.186644+00:00 heroku[run.5253]: Starting process with command `rails console`  2016-12-18T07:07:09.461403+00:00 heroku[run.5253]: Process exited with status 0  2016-12-18T07:07:09.459229+00:00 heroku[run.5253]: State changed from up to complete  2016-12-18T07:08:01.251294+00:00 app[api]: Starting process with command `spring stop` by user yaphats280396@gmail.com  2016-12-18T07:08:06.994287+00:00 heroku[run.2057]: Awaiting client  2016-12-18T07:08:07.013915+00:00 heroku[run.2057]: Starting process with command `spring stop`  2016-12-18T07:08:07.238356+00:00 heroku[run.2057]: State changed from starting to up  2016-12-18T07:08:11.161840+00:00 heroku[run.2057]: State changed from up to complete  2016-12-18T07:08:11.142680+00:00 heroku[run.2057]: Process exited with status 1  2016-12-18T07:18:42.513123+00:00 heroku[slug-compiler]: Slug compilation started  2016-12-18T07:18:42.513132+00:00 heroku[slug-compiler]: Slug compilation finished  2016-12-18T07:18:42.641136+00:00 heroku[web.1]: State changed from crashed to starting  2016-12-18T07:18:42.376404+00:00 app[api]: Release v7 created by user yaphats280396@gmail.com  2016-12-18T07:18:42.376404+00:00 app[api]: Deploy 0f0c253 by user yaphats280396@gmail.com  2016-12-18T07:18:48.864292+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 56507 -e production`  2016-12-18T07:18:51.479943+00:00 heroku[web.1]: Process exited with status 127  2016-12-18T07:18:51.513045+00:00 heroku[web.1]: State changed from starting to crashed  2016-12-18T07:18:51.514288+00:00 heroku[web.1]: State changed from crashed to starting  2016-12-18T07:18:51.351956+00:00 app[web.1]: bash: bin/rails: No such file or directory  2016-12-18T07:18:56.601461+00:00 heroku[web.1]: Starting process with command `bin/rails server -p 47201 -e production`  2016-12-18T07:18:58.427067+00:00 app[web.1]: bash: bin/rails: No such file or directory  2016-12-18T07:18:58.490908+00:00 heroku[web.1]: Process exited with status 127  2016-12-18T07:18:58.523092+00:00 heroku[web.1]: State changed from starting to crashed  2016-12-18T07:19:26.047830+00:00 app[api]: Starting process with command `bundle exec rake db:migrate` by user yaphats280396@gmail.com  2016-12-18T07:19:31.378985+00:00 heroku[run.4257]: Awaiting client  2016-12-18T07:19:31.407367+00:00 heroku[run.4257]: Starting process with command `bundle exec rake db:migrate`  2016-12-18T07:19:31.663915+00:00 heroku[run.4257]: State changed from starting to up  2016-12-18T07:19:37.609181+00:00 heroku[run.4257]: State changed from up to complete  2016-12-18T07:19:37.628694+00:00 heroku[run.4257]: Process exited with status 0  2016-12-18T07:19:47.465402+00:00 app[api]: Starting process with command `rails console` by user yaphats280396@gmail.com  2016-12-18T07:19:53.296424+00:00 heroku[run.8574]: Awaiting client  2016-12-18T07:19:53.460124+00:00 heroku[run.8574]: State changed from starting to up  2016-12-18T07:19:53.343683+00:00 heroku[run.8574]: Starting process with command `rails console`  2016-12-18T07:19:57.742878+00:00 heroku[run.8574]: State changed from up to complete  2016-12-18T07:19:57.727626+00:00 heroku[run.8574]: Process exited with status 0  2016-12-18T07:20:40.222378+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=mighty-island-98480.herokuapp.com request_id=221c14dd-1775-4891-83ce-e8a24678075f fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  2016-12-18T07:20:40.532629+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=mighty-island-98480.herokuapp.com request_id=5b2ff337-7233-49bc-a4a8-6b8dd1d485ff fwd="203.205.28.130" dyno= connect= service= status=503 bytes=  

I've deployed a couple of apps to Heroku before but never come across this weird situation. I will provide further files/details if needed.

TurboLinks with Angular

Posted: 17 Dec 2016 11:27 PM PST

I'm running Angular 1.6 along with TurboLinks 5. For the most part, things are working well. I disabled TurboLinks cache and am manually bootstrapping Angular per some of the suggestions on this post: Using angularjs with turbolinks

I have run into one issue though where I have an $interval running within a service. When changing pages via TurboLinks, Angular bootstraps again and the service creates a new interval, but the old one continues to run! Every time a page change event occurs, a new interval is created and they keep piling on top of each other.

I tried destroying the angular app when a TurboLinks link is clicked (using the code below), but that seems to cause the whole Angular app to quit working. I also can't seem to get a reference to the older interval after a page reload.

var app = angular.module('app', []);    // Bootstrap Angular on TurboLinks Page Loads  document.addEventListener('turbolinks:load', function() {      console.log('Bootstrap Angular');      angular.bootstrap(document.body, ['app']);  });    // Destroy the app before leaving -- Breaks angular on subsequent pages  document.addEventListener('turbolinks:click', function() {      console.log('Destroy Angular');      var $rootScope = app.run(['$rootScope', function($rootScope) {          $rootScope.$destroy();      }]);  });  

Without the $rootScope.$destroy() on the turbolinks:click event, everything else appears to be working as expected.

I know I could fire off an event here and kill the interval in the service, but ideally I'd like some way where this is automatically handled and ensured nothing is accidentally carried over between TurboLinks requests. Any ideas?

how to delete not saved data but i have assigned this data with build or new in rails?

Posted: 17 Dec 2016 09:43 PM PST

I have assigned record like this

profile_image = current_user.profile_images.build(params_profile_image)  

But I don't want to save this record any more. Now how can I delete this profile_image unsaved record ?

get :index, undefined method `respond_with' for Api::V1::EventsController

Posted: 17 Dec 2016 09:31 PM PST

When sending a get request to http://localhost:3000/api/v1/events to test that my API works, I get the following error.

     Failure/Error: respond_with Event.all         NoMethodError:         undefined method `respond_with' for #<Api::V1::EventsController:0x007ff018f2edc8>         Did you mean?  respond_to  

My EventsController looks like this

class Api::V1::EventsController < ApplicationController    respond_to? :json      def index      respond_with Event.all    end  

What am I doing wrong?

Rails 5 - Acts as Taggable On with predefined tags

Posted: 17 Dec 2016 11:20 PM PST

I'm trying to use the acts as taggable on gem with my rails 5 app.

I have a model called Proposal, which I'm trying to tag with predefined tags from my Randd::Fields model.

In my proposal.rb, I have:

class Proposal < ApplicationRecord      acts_as_taggable    acts_as_taggable_on :randd_maturities, :randd_fields, :randd_purposes, :randd_activities  

In my proposal controller, I have whitelisted the randd_fields_list attribute:

params.require(:proposal).permit(:title, :randd_fields_list)

In my Randd::Fields table, I have one record saved:

Randd::Field.all    Randd::Field Load (0.5ms)  SELECT "randd_fields".* FROM "randd_fields"   => #<ActiveRecord::Relation [#<Randd::Field id: 1, created_at: "2016-11-26 08:38:11", updated_at: "2016-11-26 08:38:11", anz_reference: "test ref", title: "test title">]>   

In the console, I'm trying to add the predefined Randd::Field.title to the proposal:

Proposal.first.randd_field_list.add(Randd::Field.find_by(id: 1).title)

But - then when I try: Proposal.first.randd_field_list, I get:

p.randd_field_list    ActsAsTaggableOn::Tagging Load (0.7ms)  SELECT "taggings".* FROM "taggings" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2  [["taggable_id", 17], ["taggable_type", "Proposal"]]    ActsAsTaggableOn::Tag Load (0.9ms)  SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'randd_fields' AND taggings.tagger_id IS NULL)  [["taggable_id", 17], ["taggable_type", "Proposal"]]   => []   

So - that hasn't worked.

How do I make the randd_field_list update with my defined tags in the Randd::Field table?

[Rails How to specify folders to which I upload files in google drive?

Posted: 18 Dec 2016 07:07 AM PST

I use gem google drive v.2.1.2, and I searched api from here.

According to this api, I can upload files by following code.

session.upload_from_file("/path/to/hoge.txt")  

In this api, no way to specify a folder to which I can upload my files.

If you know the way to specify a foloder, please tell me.

Integrating bootstrap nav-tab CSS with radio_button?

Posted: 17 Dec 2016 08:37 PM PST

How can I get the radio_button to look like nav-tabs?

<ul class="nav nav-tabs">    <%= f.radio_button :someday, "0", checked: "checked" %>    <li role="presentation"><a href="">Schedule</a></li> #Should default to class="active"    <%= f.radio_button :someday, "1" %>    <li role="presentation"><a href="">Someday</a></li>  </ul>  

So instead of the user clicking a radio_button he would click a tab.

What is the correct syntax for @pin in the new method?

Posted: 18 Dec 2016 04:14 AM PST

I know that the correct syntax for @pin in create method is

@pin = current_user.pins.build(pin_params), but I'm just not 100% sure which syntax to use in new method since it is just for initialization.

is it?

def new    @pin = Pin.new  end  

or is it?

def new    @pin = current_user.pins.build  end  

Nested Attributes Forms for Has One

Posted: 17 Dec 2016 08:10 PM PST

I am trying to use nested attribute forms with a relation that is belongs_to and has_one

I have defined the relations in my model like

class Merchant < ActiveRecord::Base      has_one :account, dependent: :destroy    class Account < ActiveRecord::Base      belongs_to :merchant  

Controller

def edit      @merchant = Merchant.find(params[:id])      @merchant.account.build      @states = State.form_selector      @products = Product.all      @properties = Property.where(property_set_id: 1)    end  

Error

NoMethodError (undefined method `build' for nil:NilClass):    app/controllers/admin/merchants_controller.rb:32:in `edit'  

How to get an item's rank in an ActiveRecord collection, with ties?

Posted: 17 Dec 2016 09:29 PM PST

I've got a collection of @players, ordered by total_points. I'm trying to figure out what position a specific @player is ranked in the collection of @players.

Example: there are 5 players, here are their total_points:

  • Player 1: 20 points
  • Player 2: 20 points
  • Player 3: 15 points
  • Player 4: 15 points
  • Player 5: 15 points

Given that we measure ties like this:

  • Player 1: Tied for 1st
  • Player 2: Tied for 1st
  • Player 3: Tied for 3rd
  • Player 4: Tied for 3rd
  • Player 5: Tied for 3rd

What's the easiest way to only show Player 4's rank? Is this possible without iterating through the entire collection? I have an idea of how I would print out the entire list by checking if the previous iterator's total_score is the same, but I don't need to display the whole list, just the rank for the current player.

In my app, there are going to be close to a thousand players, so I'm trying to find a method that will be fast to calculate.

EDIT:

Here's what I've come up with based on @max's answer:

 @grouped_players = Player.all.reorder(total_points: :desc).group(:total_points).count   our_rank = 0   tied = false   @grouped_players.each do |points, count|     if points > @player.total_points       our_rank += count     end     if points == @player.total_points       our_rank += 1       if count > 1         tied = true       end       break     end   end     puts our_rank   puts tied  

Anyone have a more elegant solution?

Rails query for a social network feed

Posted: 18 Dec 2016 02:33 AM PST

The architecture of the model is simple.

class User < ActiveRecord::Base    has_many :hunts, dependent: :destroy    has_many :user_hunts, dependent: :destroy  end    class Hunt < ApplicationRecord    belongs_to :user    has_many :user_hunts, dependent: :destroy  end    class UserHunt < ApplicationRecord    belongs_to :user    belongs_to :hunt  end   

User can create hunts . Other Users can see these hunts in their feed. They can either accept it or reject it. This would create a row in UserHunt with hunt_id and user_id. So what I want is a result of Hunt which satisfy these onditions.

  • Hunt is not his own (hunt.user_id != id)
  • User has not seen the hunt before ( This is the part which I am finding difficult to implement)

After lot of trials this is what I came up with.

Hunt.left_outer_joins(:user_hunts)      .where('user_hunts.user_id != ? OR user_hunts.user_id is null AND hunts.user_id != ?',id,id)  

But this has a problem of selecting hunts which other users have subscribed.

This is a common scenario in websites I believe. But I was not able to find any solution here. Thanks in advance.

How to add a where class to find all records with datetime expiring in x days

Posted: 17 Dec 2016 08:40 PM PST

I have a model with a datetime column that is the expire_at.

So I want to find all records that are expiring in 3 days.

def find_expring_in(days)    Products.where(expiring_at: ???? )  end  

Rails 5 - Rake task to import data from CSV file

Posted: 17 Dec 2016 10:41 PM PST

I am trying to follow the GoRails tutorial for importing data from a csv file.

In my rails app, I have saved the file as for_codes.csv.

In my lib/tasks folder, I have made a file called: import.rake

In my input.rake file, I have:

require 'csv'  namespace :import do      desc "import research fields from csv"    task rannd_fields: :environment do      filename = File.join Rails.root, 'for_codes.csv'      counter = 0        CSV.foreach(filename, headers: true) do | row |        p row ["anz_reference"]        for_code = Randd::Field.create(:anz_reference: row["anz_reference"], title: title)        counter += 1 if randd_field.persisted?      end      puts "Imported #{counter} field codes"    end  end  

When I then try this in the console, with:

bundle exec rake import:randd_fields  

I get an error that says:

NameError: undefined local variable or method `randd_fields' for main:Object  

The model I'm trying to make records on is called:

class Randd::Field < ApplicationRecord  

The table in the database is called:

randd_fields  

Can anyone see what I need to do to rake this task?

Jekyll serve not working- Cannot find _fluidbox.scss?

Posted: 18 Dec 2016 02:08 AM PST

Configuration file: C:/Users/Simon/Documents/other/Jekyll-project/_config.yml  Configuration file: C:/Users/Simon/Documents/other/Jekyll-project/_config.yml              Source: C:/Users/Simon/Documents/other/Jekyll-project         Destination: C:/Users/Simon/Documents/other/Jekyll-project/_site   Incremental build: disabled. Enable with --incremental        Generating...  Error in _assets/stylesheets/light.scss:50 File to import not found or unreadab  e: ../bower/fluidbox/src/css/_fluidbox.scss.  Load paths:    C:/Users/Simon/Documents/other/Jekyll-project/_assets/css    C:/Users/Simon/Documents/other/Jekyll-project/_assets/stylesheets    C:/Users/Simon/Documents/other/Jekyll-project/_assets/images    C:/Users/Simon/Documents/other/Jekyll-project/_assets/img    C:/Users/Simon/Documents/other/Jekyll-project/_assets/fonts    C:/Users/Simon/Documents/other/Jekyll-project/_assets/javascripts    C:/Users/Simon/Documents/other/Jekyll-project/_assets/js    C:/Users/Simon/Documents/other/Jekyll-project/_assets/bower    C:/Users/Simon/Documents/other/Jekyll-project/_vendor    Liquid Exception: File to import not found or unreadable: ../bower/fluidbox/s  c/css/_fluidbox.scss. Load paths: C:/Users/Simon/Documents/other/Jekyll-project  _assets/css C:/Users/Simon/Documents/other/Jekyll-project/_assets/stylesheets C  /Users/Simon/Documents/other/Jekyll-project/_assets/images C:/Users/Simon/Docum  nts/other/Jekyll-project/_assets/img C:/Users/Simon/Documents/other/Jekyll-proj  ct/_assets/fonts C:/Users/Simon/Documents/other/Jekyll-project/_assets/javascri  ts C:/Users/Simon/Documents/other/Jekyll-project/_assets/js C:/Users/Simon/Docu  ents/other/Jekyll-project/_assets/bower C:/Users/Simon/Documents/other/Jekyll-p  oject/_vendor in /_layouts/post.html  jekyll 3.3.1 | Error:  File to import not found or unreadable: ../bower/fluidbo  /src/css/_fluidbox.scss.  Load paths:    C:/Users/Simon/Documents/other/Jekyll-project/_assets/css    C:/Users/Simon/Documents/other/Jekyll-project/_assets/stylesheets    C:/Users/Simon/Documents/other/Jekyll-project/_assets/images    C:/Users/Simon/Documents/other/Jekyll-project/_assets/img    C:/Users/Simon/Documents/other/Jekyll-project/_assets/fonts    C:/Users/Simon/Documents/other/Jekyll-project/_assets/javascripts    C:/Users/Simon/Documents/other/Jekyll-project/_assets/js    C:/Users/Simon/Documents/other/Jekyll-project/_assets/bower    C:/Users/Simon/Documents/other/Jekyll-project/_vendor  

I have no idea what this means. All I did was download a jekyll theme here: http://chalk.nielsenramon.com,

change a few things in _config.yml (Just the twitter/github and profile usernames) and run jekyll serve command in my cmd. This is the error message that shows up. I haven't done jekyll very long, so I apologize

Rails Strong Params not recognizing params sent through Ajax Post

Posted: 17 Dec 2016 06:52 PM PST

Hello I am trying to sent the following params from the front end to my backend rails controller where I have strong params set up My ajax call looks like this

$("#send").click(function() {          var message = $("#message").val();          var listing_id = $("#listing_id").val();          d = {              'message': message,               'listing_id': listing_id,              'status': "pending"          };            $.ajax({             type: "POST",             url: "/crecits",             data: d          });      });   

This is sending in the following parameter to the controller

Parameters: {"message"=>"Hello world", "listing_id"=>"1", "status"=>"some status"}  

And then my controller that handles this looks like this

class CrecitsController < ApplicationController  ..  def create          @crecit = current_user.crecits.new(crecits_params)          respond_to do |format|            if @crecit.save              format.html { redirect_to @crecit, notice: 'Request Sent' }            else              format.html { redirect_to listings_path, notice: 'your request can not be sent' }            end          end      end    private        def crecits_params           params.require(:crecit).permit(:user_id, :status, :listing_id,    :message)        end  ..  end  

No comments:

Post a Comment