Sunday, June 26, 2016

input-group-btn with SimpleForm and HAML | Fixed issues

input-group-btn with SimpleForm and HAML | Fixed issues


input-group-btn with SimpleForm and HAML

Posted: 26 Jun 2016 07:32 AM PDT

I'm tring to create an input field with button on the right side of the input. From the Bootstrap's doc, it'll be something like this:

<div class="input-group">    <input type="text" class="form-control" placeholder="Search for...">    <span class="input-group-btn">      <button class="btn btn-default" type="button">Go!</button>    </span>  </div>  

With HAML and SimpleForm, I tried this code:

= simple_form_for @product do |f|    .input-group      = f.input :url, as: "string", input_html: { class: "input-lg" }, label: false, required: true do        %span.input-group-btn        = f.submit "Track!", class: "btn btn-lg btn-success"  

However, it only generated this code (without the input):

<div class="input-group">      <div class="form-group string required product_url">          <span class="input-group-btn"></span>          <input type="submit" name="commit" value="Track!" class="btn btn-lg btn-success">      </div>  </div>  

How do correct this code? Thanks in advance.

Stock maintaining in rails application

Posted: 26 Jun 2016 07:14 AM PDT

I would like to know the remaining stock after making the purchasing and sales in rails way.

Please find below the screenshot for the reference;

Screenshot.png

I have prepared the purchased table but unable to tackle the idea of handling remaining stock.

Any suggestions are most welcome.

Thank you in advance.

Use Ruby database on Rails

Posted: 26 Jun 2016 07:42 AM PDT

I created a mysql database with Ruby. I want to use it on my Rails app. How I can do it? How can I read data with Rails without any database?

How do I access both associations in a self referential has_many through relationship?

Posted: 26 Jun 2016 07:04 AM PDT

If I have an association class like:

class TranslationAssociation < ActiveRecord::Base      belongs_to :child, class_name: "Translation"    belongs_to :translation  

And a class like:

class Translation < ActiveRecord::Base      has_many :translation_associations    has_many :children, through: :translation_associations  

I get the children just fine. But if I am a child, how do I create a relationship to get the parent?

Rails 4 and Google Experiments - web server rejects utm_expid

Posted: 26 Jun 2016 06:09 AM PDT

I have a Rails 4.2 app hosted on Heroku. I am using a PPC campaign through Google to drive traffic and am trying to leverage Google Experiments to A/B test two landing pages (landing1.html.erb and landing2.html.erb). Google requires that the Javascript code to run the experiment be placed immediately after the <head> tag but only for the original (landing1) of the two variations.

I placed this in my application's layout page directly after the <head> tag (id number changed for this example):

<head>    <% if (request.fullpath == '/landing1') && Rails.env.production? %>      <!-- Google Analytics Content Experiment code -->      <script>function utmx_section(){}function utmx(){}(function(){var      k='111111111-0',d=document,l=d.location,c=d.cookie;      if(l.search.indexOf('utm_expid='+k)>0)return;      function f(n){if(c){var i=c.indexOf(n+'=');if(i>-1){var j=c.      indexOf(';',i);return escape(c.substring(i+n.length+1,j<0?c.      length:j))}}}var x=f('__utmx'),xx=f('__utmxx'),h=l.hash;d.write(      '<sc'+'ript src="'+'http'+(l.protocol=='https:'?'s://ssl':      '://www')+'.google-analytics.com/ga_exp.js?'+'utmxkey='+k+      '&utmx='+(x?x:'')+'&utmxx='+(xx?xx:'')+'&utmxtime='+new Date().      valueOf()+(h?'&utmxhash='+escape(h.substr(1)):'')+      '" type="text/javascript" charset="utf-8"><\/sc'+'ript>')})();      </script><script>utmx('url','A/B');</script>      <!-- End of Google Analytics Content Experiment code -->    <% end %>  

Navigating directly to this page on Heroku renders it properly. Viewing source of the page confirms the script is in the <head>. There are no errors in the javascript console.

However when using Google Analytics to validate the page Google returns the following error under Experiment Code Validation:

Variant 1: Web server rejects utm_expid.

The help for this page includes the following:

To check and display pages in Google Analytics Experiments, we add the URL parameter utm_expid to original and variation pages. It seems that your web server won't accept this URL parameter. Change your server to accept parameters, or ask your webmaster for help.

I've dropped code directly on the page to render the utm_expid if I pass it in manually and it appears on the page. The logs in production appear to be clean, nothing indicating an error. I even tried adding a permit on the controller for that page for the utm_expid parameter but that had no impact.

Completely at a loss here and could use some direction.

how to create new rails generator for droping a table

Posted: 26 Jun 2016 07:41 AM PDT

I creation an app that needs to be able to create and drop tables on the fly, on create it's pretty simple I use: rails g migration User name:string but there is no generator for droping a table.

I want to make it be possible to: rails g migration DropTableUser Thanks!

sharetribe sh: indexer: command not found

Posted: 26 Jun 2016 04:57 AM PDT

I just clone https://github.com/sharetribe/sharetribe open source project, I install every gem and when I try to run:

bundle exec rake ts:index  

I get the following error:

WARN You specified server rendering JS file: app/assets/webpack/server-bundle.js, but it cannot be read. You may set the server_bundle_js_file in your configuration to be "" to avoid this warning You specified server rendering JS file: app/assets/webpack/server-bundle.js, but it cannot be read. You may set the server_bundle_js_file in your configuration to be "" to avoid this warning Generating configuration to /Users/jeanosorio/Repos/sharetribe/config/development.sphinx.conf DEBUG SQL (0.6ms) DELETE FROM delayed_jobs WHERE (handler LIKE ('--- !ruby/object:ThinkingSphinx::Deltas::%') AND locked_at IS NULL AND locked_by IS NULL AND failed_at IS NULL) sh: indexer: command not found

And I can't make it work.

Ruby on rails: Has_many self referencial - List objects in view

Posted: 26 Jun 2016 04:54 AM PDT

i'm doing this tutorial http://cobwwweb.com/bi-directional-has-and-belongs-to-many-on-a-single-model-in-rails for doing a parent-child association with multiple parents for each child.

I can already associate parents with childs. But now I don't understand how can I list the parents and their children

This is my PerformanceIndicator model:

class PerformanceIndicator < ActiveRecord::Base    has_many :improvement_actions    has_ancestry        has_many :left_parent_associations, :foreign_key => :left_parent_id, :class_name => 'PerformanceIndicatorAssociation'    has_many :left_associations, :through => :left_parent_associations, :source => :right_parent      has_many :right_parent_associations, :foreign_key => :right_parent_id, :class_name => 'PerformanceIndicatorAssociation'    has_many :right_associations, :through => :right_parent_associations, :source => :left_parent      def associations      (left_associations + right_associations).flatten.uniq    end     end  

And this is my PerformanceIndicatorAssociation model:

class PerformanceIndicatorAssociation < ActiveRecord::Base    belongs_to :left_parent, :class_name => 'PerformanceIndicator'    belongs_to :right_parent, :class_name => 'PerformanceIndicator'  end  

How can I list the parents and their child like this?

Parent1    Child1    Child2  Parent2    Child1    Child2  

Multiple Domain pointing to single rails app displaying different content with the same url path

Posted: 26 Jun 2016 04:43 AM PDT

I have searched around the web and there are answers that have helped me abit, however I am still stuck, so here goes.

I a Rails 4 app that allows users to create a biography/blog and then access it using their own domain.

Users can choose from several pre-made website templates (main page, about me page, my hobbies page, etc...), and then they load up their content using a CMS. The content will then be displayed using their chosen template when visitors visit their domain.

Eg:

User 1:

Domain: www.user1.com

Template: Template A

User 2:

Domain: www.user2.com

Template: Template B

Desired Results

When a visitor visits www.user1.com, they will see the main page. When they click on "About Me", they will be redirect to www.user1.com/about-me. If a visitor visits the "About Me" page for user 2, they will see www.user2.com/about-me.

My question here is, how do I set this up?

Based on this answer: Rails routing to handle multiple domains on single application

class Domain    def self.matches?(request)      request.domain.present? && request.domain != "mydomain.com"    end  end    ------in routes.rb------    require 'subdomain'  constraints(Domain) do    match '/' => 'blogs#show'  end  

I know I can route a different domain compared to mine to a separate controller, however, I need to route it to different template controllers which can change at any moment (users can change templates at will).

I know I can set up a general controller that can read incoming requests, then based on the hostname, I can extract the appropriate template and then redirect the request to that template's controller (eg: Template1Controller), however the url gets messed up, becoming something like "/template/template1/index" or "/template/template1/about-me" which is very bad and ugly. Furthermore, it will be extremely tricky to handle paths specific to only some templates (Template A might have a "My Resume" page while template B might have a "Family History" page instead).

Is there a way to do this?

I have thought about a method where I have a single controller that will handle everything (without redirects) and then just calls render template1/index, but I think it is a bad way of doing it (different template might need different data in each page).

Btw, this will be hosted on EC2.

EDIT What I am looking to implement is quite similar to this question Mapping multiple domain names to different resources in a Rails app , but unfortunately no answers then. Im hoping 5 years later, someone might know how to get this done.

Thanks!

Rails: How to store date in "Chennai" Timezone in the database

Posted: 26 Jun 2016 05:19 AM PDT

In the rails application by default created_at and updated_at filed are stored in UTC format. i want to store created_at and updated_at field in my local timezone i.e in "Chennai" Timezone.

I wrote below to lines in my application.rb file but still my created_at and updated_at fields dates are saved in UTC timezone and not in my local timezone.

 config.time_zone = 'Chennai'   config.active_record.default_timezone = :local  

Please let me know what wrong i am doing here??

Thanks,

Sanjay Salunkhe

write a spec for mandrill-api sending template email

Posted: 26 Jun 2016 04:27 AM PDT

I'm new to ruby and I've been trying to write a spec for simple function that sends email via mandrill-api (which is connected to Mailchimp).

I'm not using ActionMailer. only the mandrill-api gem.

I'm a bit lost, what's the perfect approach for this ?

I tried VCR, but I don't know how to make it works.

Error upgrading rails from 5.0.0.rc1 to 5.0.0.rc2

Posted: 26 Jun 2016 04:19 AM PDT

OS: Mac OS X El-Captain current rails version: 5.0.0.rc1 ruby version: 2.3.1p112

I'm having following error. Googling and searching on Stack Overflow didn't give any results.

gem install rails -v 5.0.0.rc2

ERROR:  While executing gem ... (Gem::Resolver::Molinillo::CircularDependencyError)      There is a circular dependency between camping and rack  

uploading multiple files on carrierwave (implementing arrays) while using sqlite

Posted: 26 Jun 2016 03:42 AM PDT

I'm building a web-app using ruby on rails (4.2.5), and I need the user to be able to upload multiple files as attachments when creating an object (called "Request" in this case). I was able to implement carrierwave (0.9) and users can upload a file to each request, but turns out that the multiple files functionality requires an array-type column, which is not available as a datatype in the SQLite database which I am using. from what I gathered, it seems that you can use JSON to do that, but I don't know how that works. I would like to know how I can work around this problem and allow the user to upload multiple files to the request, even if I should use an entirely different method. Thank you

Improve query with table joins?

Posted: 26 Jun 2016 03:55 AM PDT

I want to retrieve a list of all Downloads as a result of a particular users content. For example, If I have 2 uploads, I want to filter the contents of the Download table to show only those downloads related to my Uploads.

Users {      user_id: integer  }    Upload {      upload_id: integer      user_id: integer (FK)  }    Download {      download_id: integer      upload_id: integer (FK)  }  

The downloads table is a log of every public user that has downloaded a file ("upload") on my blog. As you can see, an Upload is linked to a user (user can have many uploads) and a download is linked to an upload (one upload can be downloaded many times).

This is the solution I am using so far (it's really messy and probably very inefficient):

@user = User.find_by_id(3)  # grab a list of the User 1's upload ids, [3, 6, 2, 34, 45]  @upload_ids = @user.uploads.map { |u| u.upload_id }    # now find all Downloads that have these id numbers in their upload_id  @downloads = Download.where(:upload_id => @upload_ids)  

I'm sure there is a way to achieve this with table joins. UPDATE: All associations are explicitly configured.

Update column in database from model

Posted: 26 Jun 2016 04:20 AM PDT

So I have a User model and a Post model

Post belongs to a User

Post has a field in the database called score

In the Post model I have a method called score which gives the post a score based on the fields (needs to be done this way):

def score     score = 0       if self.title.present?       score += 5     end     if self.author.present?       score += 5     end     if self.body.present?       score += 5     end       score    end  

The Question:

There are loads of Users and loads of Posts. So What I'm trying to do is after the score is worked out, I want to save it to the Post score field in the database for each Post. The score should be updated if the user updates the Post.

I have looked at using after_update :score! but don't understand how to apply the logic

Rails does not add new tables to schema.rb in non public schema

Posted: 26 Jun 2016 04:18 AM PDT

I created a new table via rails migration in Postgres in a new schema (name - "concluded")

class CreateWeeklyLeaderboard < ActiveRecord::Migration    def up      execute('create schema concluded')      create_table('concluded.weekly_leaderboard') do |t|        t.date :week_start_date        t.references :user        t.integer :rank        t.integer :points        t.timestamps null: true      end    end      def down      drop_table('concluded.weekly_leaderboard')      execute('drop schema concluded')    end  end  

Database configuration:

development:    adapter: postgresql    encoding: utf8    database: duggout    host: 127.0.0.1    pool: 5    username: postgres    password: pass    schema_search_path: public, concluded  

The create_table in schema.rb appears like below:

create_table "weekly_leaderboard", force: :cascade do |t|     t.date     "week_start_date"     t.integer  "user_id"     t.integer  "rank"     t.integer  "points"     t.datetime "created_at"     t.datetime "updated_at"   end  

As you see, the schema name does not appear in this file. How to ensure schema name is present in schema.rb for non public tables?

How to pass text from view to javascript

Posted: 26 Jun 2016 03:23 AM PDT

Hi there i have problem with Rails & Javascript. Here is my table in view.

<table>    <thead>      <tr>        <th>No</th>        <th>Name</th>      </tr>    </thead>    <tbody>        <tr id="adminrow">          <td>            1          </td>          <td>            <a href="#" id="select_name">John</a>          </td>        </tr>        <tr id="adminrow">          <td>            2          </td>          <td>            <a href="#" id="select_name">Alex</a>          </td>        </tr>        <tr id="adminrow">          <td>            3          </td>          <td>            <a href="#" id="select_name">Paul</a>          </td>        </tr>    </tbody>  </table>  

and my JS is

$('#select_name').click(function(event){      var username = $("#select_name").text();      console.log(username);  });  

I have lot of names in my table, but JS printed first name in console. How can I print each name in the table to console?

Rails uniqueness validator fails on weird double xhr request

Posted: 26 Jun 2016 02:40 AM PDT

I have a form that sends with { remote: true } and an Adopter model that has a uniqueness validator on the email field. Now I have a weird bug in production environment (and I wasn't able to reproduce it in development):

Sometimes if people are creating an Adopter the post request will be sent twice (most of the time everything works fine). When that happens, my Rails app creates two Adopters with the same email. The following is a excerpt from the issue causing requests (I removed boring and private stuff):

Started GET "/" for 123.456.789.012 at 2016-06-25 15:03:37 +0000  Processing by LandingController#index as HTML  request http://ipinfo.io/123.456.789.012  {    "ip": "123.456.789.012",    "hostname": "12345678.dip0.t-ipconnect.de",    "city": "",    "region": "",    "country": "DE",    "loc": "1.0000,1.0000",    "org": "Organistion name"  }    Rendered landing/index.html.slim within layouts/application (1.6ms)    Rendered layouts/application/_head.html.slim (2.0ms)    Rendered layouts/application/_ga.html.slim (0.1ms)  Completed 200 OK in 39ms (Views: 6.8ms | ActiveRecord: 0.0ms)  Started POST "/adopters" for 123.456.789.012 at 2016-06-25 15:05:42 +0000  Processing by AdoptersController#create as JS    Parameters: {"utf8"=>"✓", "name"=>"Mika", "answer"=>{"for"=>"friend", "for_precise"=>"male_friend", "nature"=>"humorous", "interests"=>["technology", "music"]}, "email"=>"nobody@shouldknow.com"}  request http://ipinfo.io/123.456.789.012  {    "ip": "123.456.789.012",    "hostname": "12345678.dip0.t-ipconnect.de",    "city": "",    "region": "",    "country": "DE",    "loc": "1.0000,1.0000",    "org": "Organistion name"  }    Adopter Load (0.7ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."referral_code" = $1 LIMIT 1  [["referral_code", "97f32b"]]    CACHE (0.0ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."referral_code" = $1 LIMIT 1  [["referral_code", "97f32b"]]     (0.3ms)  BEGIN     (0.4ms)  SELECT COUNT(*) FROM "adopters" WHERE "adopters"."sign_up_ip" = $1  [["sign_up_ip", "123.456.789.012/32"]]    Adopter Exists (0.9ms)  SELECT  1 AS one FROM "adopters" WHERE "adopters"."email" = 'nobody@shouldknow.com' LIMIT 1    Adopter Exists (0.4ms)  SELECT  1 AS one FROM "adopters" WHERE "adopters"."referral_code" IS NULL LIMIT 1    Adopter Load (0.4ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."referral_code" = $1 LIMIT 1  [["referral_code", "58b7fd"]]     (0.2ms)  SELECT COUNT(*) FROM "adopters" WHERE "adopters"."sign_up_ip" = $1  [["sign_up_ip", "89.15.237.123/32"]]    Adopter Exists (0.4ms)  SELECT  1 AS one FROM "adopters" WHERE ("adopters"."email" = 'lukas.thorr@web.de' AND "adopters"."id" != 52) LIMIT 1    Adopter Exists (0.3ms)  SELECT  1 AS one FROM "adopters" WHERE ("adopters"."referral_code" = '97f32b' AND "adopters"."id" != 52) LIMIT 1    SQL (2.0ms)  UPDATE "adopters" SET "referred_count" = $1, "updated_at" = $2 WHERE "adopters"."id" = $3  [["referred_count", 1], ["updated_at", "2016-06-25 15:05:42.492589"], ["id", 52]]    SQL (1.2ms)  INSERT INTO "adopters" ("name", "email", "gift_for_person", "gift_for_person_nature", "gift_for_person_interests", "sign_up_ip", "referred_by", "locale", "created_at", "updated_at", "referral_code", "referred_count") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id"  [["name", "Mika"], ["email", "nobody@shouldknow.com"], ["gift_for_person", "male_friend"], ["gift_for_person_nature", "humorous"], ["gift_for_person_interests", "[\"technology\",\"music\"]"], ["sign_up_ip", "123.456.789.012/32"], ["referred_by", 52], ["locale", "de"], ["created_at", "2016-06-25 15:05:42.484886"], ["updated_at", "2016-06-25 15:05:42.484886"], ["referral_code", "58b7fd"], ["referred_count", 0]]  [ActiveJob]   Adopter Load (0.6ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."id" = $1 LIMIT 1  [["id", 54]]  [ActiveJob] [ActionMailer::DeliveryJob] [3f82f6c1-3f4e-4411-a377-2a667d32559f] Performing ActionMailer::DeliveryJob from Inline(mailers) with arguments: "AdopterMailer", "signup_email", "deliver_now", gid://Mycoolsite-prelauncher/Adopter/54  [ActiveJob] [ActionMailer::DeliveryJob] [3f82f6c1-3f4e-4411-a377-2a667d32559f]   Rendered adopter_mailer/signup_email.html.slim (3.0ms)  [ActiveJob] [ActionMailer::DeliveryJob] [3f82f6c1-3f4e-4411-a377-2a667d32559f]   AdopterMailer#signup_email: processed outbound mail in 8.1ms  Started POST "/adopters" for 123.456.789.012 at 2016-06-25 15:05:44 +0000  Processing by AdoptersController#create as JS    Parameters: {"utf8"=>"✓", "name"=>"Mika", "answer"=>{"for"=>"friend", "for_precise"=>"male_friend", "nature"=>"humorous", "interests"=>["technology", "music"]}, "email"=>"nobody@shouldknow.com"}  request http://ipinfo.io/123.456.789.012  {    "ip": "123.456.789.012",    "hostname": "12345678.dip0.t-ipconnect.de",    "city": "",    "region": "",    "country": "DE",    "loc": "1.0000,1.0000",    "org": "Organistion name"  }    Adopter Load (1.2ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."referral_code" = $1 LIMIT 1  [["referral_code", "97f32b"]]    CACHE (0.0ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."referral_code" = $1 LIMIT 1  [["referral_code", "97f32b"]]     (0.2ms)  BEGIN     (0.3ms)  SELECT COUNT(*) FROM "adopters" WHERE "adopters"."sign_up_ip" = $1  [["sign_up_ip", "123.456.789.012/32"]]    Adopter Exists (0.5ms)  SELECT  1 AS one FROM "adopters" WHERE "adopters"."email" = 'nobody@shouldknow.com' LIMIT 1    Adopter Exists (0.3ms)  SELECT  1 AS one FROM "adopters" WHERE "adopters"."referral_code" IS NULL LIMIT 1    Adopter Load (0.2ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."referral_code" = $1 LIMIT 1  [["referral_code", "860fc4"]]     (0.2ms)  SELECT COUNT(*) FROM "adopters" WHERE "adopters"."sign_up_ip" = $1  [["sign_up_ip", "89.15.237.123/32"]]    Adopter Exists (0.4ms)  SELECT  1 AS one FROM "adopters" WHERE ("adopters"."email" = 'lukas.thorr@web.de' AND "adopters"."id" != 52) LIMIT 1    Adopter Exists (0.3ms)  SELECT  1 AS one FROM "adopters" WHERE ("adopters"."referral_code" = '97f32b' AND "adopters"."id" != 52) LIMIT 1  [ActiveJob] [ActionMailer::DeliveryJob] [3f82f6c1-3f4e-4411-a377-2a667d32559f]   Sent mail to nobody@shouldknow.com (1613.9ms)  [ActiveJob] [ActionMailer::DeliveryJob] [3f82f6c1-3f4e-4411-a377-2a667d32559f] Date: Sat, 25 Jun 2016 15:05:42 +0000  From: Mycoolsite <subscribed@mysite.io>  To: nobody@shouldknow.com  Message-ID: <576e9dc67f160_83f98bcce081c5454@1c50fd29020a.mail>  Subject: Mycoolsite - Deine Anmeldung  Mime-Version: 1.0  Content-Type: text/html;   charset=UTF-8  Content-Transfer-Encoding: quoted-printable  some email content    [ActiveJob] [ActionMailer::DeliveryJob] [3f82f6c1-3f4e-4411-a377-2a667d32559f] Performed ActionMailer::DeliveryJob from Inline(mailers) in 1625.69ms  [ActiveJob] Enqueued ActionMailer::DeliveryJob (Job ID: 3f82f6c1-3f4e-4411-a377-2a667d32559f) to Inline(mailers) with arguments: "AdopterMailer", "signup_email", "deliver_now", gid://Mycoolsite-prelauncher/Adopter/54     (1.3ms)  COMMIT    SQL (62.8ms)  UPDATE "adopters" SET "referred_count" = $1, "updated_at" = $2 WHERE "adopters"."id" = $3  [["referred_count", 1], ["updated_at", "2016-06-25 15:05:44.074420"], ["id", 52]]    SQL (0.6ms)  INSERT INTO "adopters" ("name", "email", "gift_for_person", "gift_for_person_nature", "gift_for_person_interests", "sign_up_ip", "referred_by", "locale", "created_at", "updated_at", "referral_code", "referred_count") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING "id"  [["name", "Mika"], ["email", "nobody@shouldknow.com"], ["gift_for_person", "male_friend"], ["gift_for_person_nature", "humorous"], ["gift_for_person_interests", "[\"technology\",\"music\"]"], ["sign_up_ip", "123.456.789.012/32"], ["referred_by", 52], ["locale", "de"], ["created_at", "2016-06-25 15:05:44.068500"], ["updated_at", "2016-06-25 15:05:44.068500"], ["referral_code", "860fc4"], ["referred_count", 0]]  Completed 200 OK in 1716ms (Views: 0.3ms | ActiveRecord: 9.1ms)  [ActiveJob]   Adopter Load (4.3ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."id" = $1 LIMIT 1  [["id", 55]]  [ActiveJob] [ActionMailer::DeliveryJob] [d91eebb4-14ce-43e3-845c-6655c293de60] Performing ActionMailer::DeliveryJob from Inline(mailers) with arguments: "AdopterMailer", "signup_email", "deliver_now", gid://Mycoolsite-prelauncher/Adopter/55  [ActiveJob] [ActionMailer::DeliveryJob] [d91eebb4-14ce-43e3-845c-6655c293de60]   Rendered adopter_mailer/signup_email.html.slim (1.7ms)  [ActiveJob] [ActionMailer::DeliveryJob] [d91eebb4-14ce-43e3-845c-6655c293de60]   AdopterMailer#signup_email: processed outbound mail in 4.0ms  Started GET "/rank/58b7fd" for 123.456.789.012 at 2016-06-25 15:05:44 +0000  Processing by AdoptersController#refer as HTML    Parameters: {"code"=>"58b7fd"}  request http://ipinfo.io/123.456.789.012  {    "ip": "123.456.789.012",    "hostname": "12345678.dip0.t-ipconnect.de",    "city": "",    "region": "",    "country": "DE",    "loc": "1.0000,1.0000",    "org": "Organistion name"  }    Adopter Load (0.8ms)  SELECT  "adopters".* FROM "adopters" WHERE "adopters"."referral_code" = $1 LIMIT 1  [["referral_code", "58b7fd"]]     (0.6ms)  SELECT COUNT(*) FROM "adopters" WHERE "adopters"."referred_by" = $1  [["referred_by", 54]]     (0.8ms)          SELECT * FROM (          SELECT adopters.id as id, adopters.referred_count as referred_count, row_number() over(order by adopters.referred_count desc) as rn FROM adopters        ) t where id = 54      Adopter Load (0.6ms)  SELECT  "adopters".* FROM "adopters"  ORDER BY "adopters"."referred_count" DESC, "adopters"."created_at" ASC LIMIT 15    Rendered adopters/refer.html.slim within layouts/application (7.1ms)    Rendered layouts/application/_head.html.slim (1.9ms)    Rendered layouts/application/_ga.html.slim (0.1ms)  Completed 200 OK in 29ms (Views: 9.0ms | ActiveRecord: 2.8ms)  [ActiveJob] [ActionMailer::DeliveryJob] [d91eebb4-14ce-43e3-845c-6655c293de60]   Sent mail to nobody@shouldknow.com (1356.5ms)  [ActiveJob] [ActionMailer::DeliveryJob] [d91eebb4-14ce-43e3-845c-6655c293de60] Date: Sat, 25 Jun 2016 15:05:44 +0000  From: Mycoolsite <subscribed@mysite.io>  To: nobody@shouldknow.com  Message-ID: <576e9dc8265ef_83f98bc2ae3e4546d8@1c50fd29020a.mail>  Subject: Mycoolsite - Deine Anmeldung  Mime-Version: 1.0  Content-Type: text/html;   charset=UTF-8  Content-Transfer-Encoding: quoted-printable    some email content again    [ActiveJob] [ActionMailer::DeliveryJob] [d91eebb4-14ce-43e3-845c-6655c293de60] Performed ActionMailer::DeliveryJob from Inline(mailers) in 1363.09ms  [ActiveJob] Enqueued ActionMailer::DeliveryJob (Job ID: d91eebb4-14ce-43e3-845c-6655c293de60) to Inline(mailers) with arguments: "AdopterMailer", "signup_email", "deliver_now", gid://Mycoolsite-prelauncher/Adopter/55     (1.1ms)  COMMIT  Completed 200 OK in 1491ms (Views: 0.2ms | ActiveRecord: 72.7ms)  

This is the Adopter#create action (which is being called twice):

  def create      ref_code = cookies[:h_ref]        @adopter = Adopter.new      @adopter.name = params[:name]      @adopter.email = params[:email]      @adopter.gift_for_person = params[:answer][:for_precise] if !params[:answer][:for_precise].blank?      @adopter.gift_for_person = params[:answer][:for] if params[:answer][:for_precise].blank?      @adopter.gift_for_person_nature = params[:answer][:nature]      @adopter.gift_for_person_interests = params[:answer][:interests].to_json      @adopter.sign_up_ip = request.remote_ip      if ref_code && Adopter.find_by(referral_code: ref_code)        @adopter.referrer = Adopter.find_by(referral_code: ref_code)      end      @adopter.locale = I18n.locale        respond_to do |format|        if @adopter.save          cookies[:h_email] = { value: @adopter.email }          #format.html { redirect_to rank_path(code: @adopter.referral_code) }          format.js {             render :js => "window.location = '#{rank_path(code: @adopter.referral_code)}'"          }        else          logger.info("Error saving user with email, #{@adopter.email}")          # redirect_to root_path, alert: 'Something went wrong!'            # format.js {  flash[:notice] = @adopter.errors }          format.js { flash[:notice] = @adopter.errors }        end      end    end  

This is my Adopter model:

require 'adopters_helper'    class Adopter < ActiveRecord::Base    belongs_to :referrer, class_name: 'Adopter', foreign_key: 'referred_by'    has_many :referrals, class_name: 'Adopter', foreign_key: 'referred_by'      validate :not_more_than_two_adopters_per_ip    validates :email, presence: true, uniqueness: true, format: {      with: /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/i,      message: 'Invalid email format.'    }    validates :referral_code, uniqueness: true    validates :name, :locale, presence: true, allow_blank: false      before_create :create_referral_code    after_create :send_welcome_email    before_create :compute_queue_positions      def rank      row_number_tupel = ActiveRecord::Base.connection.execute("        SELECT * FROM (          SELECT adopters.id as id, adopters.referred_count as referred_count, row_number() over(order by adopters.referred_count desc) as rn FROM adopters        ) t where id = #{self.id}      ")        row_number_tupel[0]['rn']    end      private      def create_referral_code        self.referral_code = AdoptersHelper.unused_referral_code      end        def not_more_than_two_adopters_per_ip        if !Rails.env.development?          adopter_count_with_current_ip = Adopter.where(sign_up_ip: sign_up_ip).count          if adopter_count_with_current_ip >= 3            errors.add(:sign_up_ip, I18n.t('activerecord.errors.models.adopter.attributes.sign_up_ip.max_ips'))          end        end      end        def send_welcome_email        AdopterMailer.signup_email(self).deliver_later      end        def compute_queue_positions        self.referred_count = 0          if !self.referrer.blank?          self.referrer.update_attributes! referred_count: (self.referrer.referred_count + 1)        end      end  end  

So basically there are two issues. First one, that sometimes the Post request is being sent and processed twice. And second one, that if the first one happens, the uniqueness validator fails.

How do I restrict access to the index action of my resource, but not to the individual record that belongs to that user?

Posted: 26 Jun 2016 02:40 AM PDT

So this is what the truncated version of my ability.rb looks like:

class Ability    include CanCan::Ability      def initialize(user)      alias_action :create, :read, :update, :destroy, to: :crud        user ||= User.new # guest user (not logged in)      if user.has_role?(:admin)        can :manage, :all      else        cannot :read, User        can :crud, User, id: user.id          # cannot :read, :users unless user.has_role? :admin      end    end  end  

My UsersController looks like this:

class UsersController < ApplicationController    load_and_authorize_resource    before_action :set_user, only: [:show, :edit, :update, :destroy]    before_action :authenticate_user!, except: [:show]    # truncated for brevity  end  

So here, what I am trying to do is for User#Index, I want to restrict that only to admin users. But at the same time, each user should be able to access their own user page.

When I try the above, which makes sense to me, I can access the /settings for the current_user, but I can also still access the Users#Index which is what I don't want.

This is what the logs look like:

Started GET "/users/1547" for 127.0.0.1 at 2016-06-26 03:39:57 -0500  DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <class:UsersController> at myapp/controllers/users_controller.rb:2)  Processing by UsersController#show as HTML    Parameters: {"id"=>"1547"}    User Load (2.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1547], ["LIMIT", 1]]    User Load (1.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1547], ["LIMIT", 1]]    Role Load (1.8ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 1547]]    CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1547], ["LIMIT", 1]]    Rendering users/show.html.erb within layouts/application    Rendered shared/_navbar.html.erb (2.4ms)    Rendered shared/_footer.html.erb (1.3ms)  Completed 200 OK in 244ms (Views: 196.4ms | ActiveRecord: 16.7ms)      Started GET "/settings" for 127.0.0.1 at 2016-06-26 03:39:59 -0500  Processing by Devise::RegistrationsController#edit as HTML    User Load (1.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1547], ["LIMIT", 1]]    Rendering devise/registrations/edit.html.erb within layouts/application    Rendered devise/registrations/edit.html.erb within layouts/application (16.7ms)    Rendered shared/_navbar.html.erb (2.8ms)    Rendered shared/_footer.html.erb (1.0ms)  Completed 200 OK in 184ms (Views: 180.4ms | ActiveRecord: 1.2ms)      Started GET "/users" for 127.0.0.1 at 2016-06-26 03:40:01 -0500  Processing by UsersController#index as HTML    User Load (2.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1547], ["LIMIT", 1]]    Role Load (2.2ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 1547]]    Rendering users/index.html.erb within layouts/application    User Load (1.3ms)  SELECT "users".* FROM "users"    Rendered users/index.html.erb within layouts/application (7.2ms)  Started GET "/users" for 127.0.0.1 at 2016-06-26 03:40:02 -0500  Processing by UsersController#index as HTML    User Load (2.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1547], ["LIMIT", 1]]    Role Load (3.8ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 1547]]    Rendering users/index.html.erb within layouts/application    User Load (51.5ms)  SELECT "users".* FROM "users"    Rendered users/index.html.erb within layouts/application (55.1ms)    Rendered shared/_navbar.html.erb (3.4ms)    Rendered shared/_footer.html.erb (1.3ms)  Completed 200 OK in 533ms (Views: 488.8ms | ActiveRecord: 5.8ms)  

But when I comment out this line: can :crud, User, id: user.id, so I only have the cannot :read, User line, it locks me out of everything as the below logs show (which is also what I don't want).

Started GET "/users" for 127.0.0.1 at 2016-06-26 03:45:39 -0500  Processing by UsersController#index as HTML    User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1547], ["LIMIT", 1]]    Role Load (1.3ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 1547]]  Redirected to http://localhost:3000/  Completed 302 Found in 19ms (ActiveRecord: 2.4ms)      Started GET "/users" for 127.0.0.1 at 2016-06-26 03:45:39 -0500  Processing by UsersController#index as HTML    User Load (1.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1547], ["LIMIT", 1]]    Role Load (2.8ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 1547]]  Redirected to http://localhost:3000/  Completed 302 Found in 24ms (ActiveRecord: 4.0ms)  

So how do I achieve what I am trying to do?

Dynamic Select Box - Populate avaliable options based on previous selection - Rails & AJAX

Posted: 26 Jun 2016 01:37 AM PDT

Dynamic Select Box - Populate avaliable options based on previous selection - Rails & AJAX

I've been trying to create a dynamic select box on my profile form where based on the university a student selects, the form automatically provides the appropriate grading scales to select as a sub select box. However the secondary selectbox (ratings) never populates..argh

Can anyone see what i'm missing here?

Routes

resources :student_profiles do      get 'update_ranks', as: 'update_ranks'    end  

Models

rating.rb      class Rating < ActiveRecord::Base      belongs_to :university_name      end    university_name.rb      class UniversityName < ActiveRecord::Base      has_many :ratings      end  

Controller

class StudentProfilesController < ApplicationController    before_action :require_user  respond_to :html, :json  def edit  @universitynames = UniversityName.all          @ratings = Rating.all         @studentprofile = StudentProfile.find(current_user.student_profile.id)    end      def update_ranks      @ratings = Rating.where("university_name_id = ?", params[:university_name_id])      respond_to do |format|        format.js    end   End  

Edit-View

<%= s.select :universityname, options_for_select(@universitynames.collect { |country|      [country.name.titleize, country.id] }, 1), {}, { id: 'universitynames_select' } %>                                <%= s.select :initialgpa, options_for_select(@ratings.collect { |rating|      [rating.name.titleize, rating.id] }, 0), {}, { id: 'ratings_select' } %>  

studentprofile.js.coffee (javascripts/updateranks.js.coffee)

 $ ->    $(document).on 'change', '#university_names_select', (evt) ->      $.ajax 'update_ranks',        type: 'GET'        dataType: 'script'        data: {          country_id: $("#university_names_select option:selected").val()        }        error: (jqXHR, textStatus, errorThrown) ->          console.log("AJAX Error: #{textStatus}")        success: (data, textStatus, jqXHR) ->          console.log("Dynamic country select OK!")  

updateranks.js.coffee (student_profiles/updateranks.js.coffee)

$("#ratings_select").empty()    .append("<%= escape_javascript(render(:partial => @ratings)) %>")  

_rating.html.erb - partial (Ratings/_rating.html.erb)

<option value="<%= rating.id %>"><%= rating.name.titleize %></option>  

I have a feeling its to do with my routes but I'm really not experiences in AJAX or JS at all...

Failure while starting rails server

Posted: 26 Jun 2016 01:20 AM PDT

While running the command rails server, I am getting following exception

[2016-06-26 13:21:57] INFO  WEBrick 1.3.1  [2016-06-26 13:21:57] INFO  ruby 2.1.3 (2014-09-19) [x86_64-linux-gnu]  [2016-06-26 13:21:57] INFO  WEBrick::HTTPServer#start: pid=2471 port=3000  [2016-06-26 13:22:08] ERROR LoadError: cannot load such file -- active_support/security_utils          /usr/lib64/ruby/gems/2.1.0/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:251:in `require'          /usr/lib64/ruby/gems/2.1.0/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:251:in `block in require'          /usr/lib64/ruby/gems/2.1.0/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:236:in `load_dependency'          /usr/lib64/ruby/gems/2.1.0/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:251:in `require'          /usr/lib64/ruby/gems/2.1.0/gems/actionpack-3.2.17/lib/action_controller/metal/http_authentication.rb:3:in `<top (required)>'          /usr/lib64/ruby/gems/2.1.0/gems/actionpack-3.2.17/lib/action_controller/base.rb:206:in `<class:Base>'          /usr/lib64/ruby/gems/2.1.0/gems/actionpack-3.2.17/lib/action_controller/base.rb:171:in `<module:ActionController>'          /usr/lib64/ruby/gems/2.1.0/gems/actionpack-3.2.17/lib/action_controller/base.rb:3:in `<top (required)>'          /usr/lib64/ruby/gems/2.1.0/gems/actionpack-3.2.17/lib/action_dispatch/middleware/static.rb:32:in `ext'          /usr/lib64/ruby/gems/2.1.0/gems/actionpack-3.2.17/lib/action_dispatch/middleware/static.rb:16:in `match?'          /usr/lib64/ruby/gems/2.1.0/gems/actionpack-3.2.17/lib/action_dispatch/middleware/static.rb:77:in `call'          /usr/lib64/ruby/gems/2.1.0/gems/railties-3.2.17/lib/rails/engine.rb:484:in `call'          /usr/lib64/ruby/gems/2.1.0/gems/railties-3.2.17/lib/rails/application.rb:231:in `call'          /usr/lib64/ruby/gems/2.1.0/gems/rack-1.4.7/lib/rack/content_length.rb:14:in `call'          /usr/lib64/ruby/gems/2.1.0/gems/railties-3.2.17/lib/rails/rack/log_tailer.rb:17:in `call'          /usr/lib64/ruby/gems/2.1.0/gems/rack-1.4.7/lib/rack/handler/webrick.rb:59:in `service'          /usr/lib64/ruby/2.1.0/webrick/httpserver.rb:138:in `service'          /usr/lib64/ruby/2.1.0/webrick/httpserver.rb:94:in `run'          /usr/lib64/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread'  [2016-06-26 13:22:08] ERROR LoadError: cannot load such file -- active_support/security_utils          /usr/lib64/ruby/gems/2.1.0/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:  

My gem file looks like this GEM remote: https://rubygems.org/

  specs:      actionmailer (3.2.17)        actionpack (= 3.2.17)        mail (~> 2.5.4)      actionpack (3.2.17)        activemodel (= 3.2.17)        activesupport (= 3.2.17)        builder (~> 3.0.0)        erubis (~> 2.7.0)        journey (~> 1.0.4)        rack (~> 1.4.5)        rack-cache (~> 1.2)        rack-test (~> 0.6.1)        sprockets (~> 2.2.1)      activemodel (3.2.17)        activesupport (= 3.2.17)        builder (~> 3.0.0)      activerecord (3.2.17)        activemodel (= 3.2.17)        activesupport (= 3.2.17)        arel (~> 3.0.2)        tzinfo (~> 0.3.29)      activeresource (3.2.17)        activemodel (= 3.2.17)        activesupport (= 3.2.17)      activesupport (3.2.17)        i18n (~> 0.6, >= 0.6.4)        multi_json (~> 1.0)      arel (3.0.3)      builder (3.0.4)      coffee-rails (3.2.2)        coffee-script (>= 2.2.0)        railties (~> 3.2.0)      coffee-script (2.4.1)        coffee-script-source        execjs      coffee-script-source (1.10.0)      erubis (2.7.0)      execjs (2.7.0)      hike (1.2.3)      i18n (0.7.0)      journey (1.0.4)      jquery-rails (3.1.4)        railties (>= 3.0, < 5.0)        thor (>= 0.14, < 2.0)      json (1.8.3)      mail (2.5.4)        mime-types (~> 1.16)        treetop (~> 1.4.8)      mime-types (1.25.1)      multi_json (1.12.1)      polyglot (0.3.5)      rack (1.4.7)      rack-cache (1.6.1)        rack (>= 0.4)      rack-ssl (1.3.4)        rack      rack-test (0.6.3)        rack (>= 1.0)      rails (3.2.17)        actionmailer (= 3.2.17)        actionpack (= 3.2.17)        activerecord (= 3.2.17)        activeresource (= 3.2.17)        activesupport (= 3.2.17)        bundler (~> 1.0)        railties (= 3.2.17)      railties (3.2.17)        actionpack (= 3.2.17)        activesupport (= 3.2.17)        rack-ssl (~> 1.3.2)        rake (>= 0.8.7)        rdoc (~> 3.4)        thor (>= 0.14.6, < 2.0)      rake (11.2.2)      rdoc (3.12.2)        json (~> 1.4)      sass (3.4.22)      sass-rails (3.2.6)        railties (~> 3.2.0)        sass (>= 3.1.10)        tilt (~> 1.3)      sprockets (2.2.3)        hike (~> 1.2)        multi_json (~> 1.0)        rack (~> 1.0)        tilt (~> 1.1, != 1.3.0)      sqlite3 (1.3.11)      thor (0.19.1)      tilt (1.4.1)      treetop (1.4.15)        polyglot        polyglot (>= 0.3.1)      tzinfo (0.3.50)      uglifier (3.0.0)        execjs (>= 0.3.0, < 3)    PLATFORMS    ruby    DEPENDENCIES    coffee-rails (~> 3.2.1)    jquery-rails    rails (= 3.2.17)    sass-rails (~> 3.2.3)    sqlite3    uglifier (>= 1.0.3)    BUNDLED WITH     1.12.5  

ActiveSupport is already present /usr/lib64/ruby/gems/2.1.0/gems/activesupport-3.2.17

Ruby version ruby 2.1.3p242 (2014-09-19 revision 47630) [x86_64-linux-gnu]

Update a variable during a search

Posted: 26 Jun 2016 12:37 AM PDT

When searching for students and showing results, I want to be able to update a field in the metric table to show how many times a student has shown up in search results.

However, every time i run the show routine i get a undefined method `id' for nil:NilClass. Why wont it find the link between the search_student and student_metric table?

searches controller

def show          @search = current_user.searches.find_by(id: params[:id])          @search.search_students.each do |s|              @studentmetrics = StudentMetric.find(s.student_metric.id)              s.student_metric.searchinclusions =  s.student_metric.searchinclusions + 1          end      end  

search model

class Search < ActiveRecord::Base     belongs_to :user        def search_students          students = StudentProfile.all          students = students.where(["name LIKE ?", "%#{name}%"]) if name.present?      return students      end  end  

student_profile model

class StudentProfile < ActiveRecord::Base     has_one :student_metric, dependent: :destroy    belongs_to :user  end  

student_metric model

class StudentMetric < ActiveRecord::Base    belongs_to :user    belongs_to :student_profile  end  

How to retrieve form elements with React's ref?

Posted: 26 Jun 2016 06:53 AM PDT

My task is to upload an image and update the user table without the page being refreshed. My search suggested to grab the form elements with refs but I'm getting, in console:

ActionController::ParameterMissing (param is missing or the value is empty: user):

app/controllers/users_controller.rb:8:in user_params' app/controllers/users_controller.rb:3:inupdate'

Routes:

Rails.application.routes.draw do    get 'welcome/index'      # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html    root 'welcome#index'    resources :users do      member do        post 'upload' => 'users#update'      end    end  end  

The app:

var User = React.createClass({      componentDidMount: function(){      // Trying so see what this shows in the browser console      var foo = $(this.refs.myForm).elements;      console.log(foo);    }.bind(this),      onUpload: function(){      var formData = $(this.refs.myForm).serialize();      $.ajax({         url: '/users/1/upload',         type: 'POST',         data: formData,         async: false,         cache: false,         contentType: false,         processData: false,         success: function (data) {             console.log("success: " + data);         },         error: function () {             alert("error in ajax form submission");         }      });    },    render: function(){      return(        <div>          <form ref="myForm" remote="true">            <input type="file" name="user[avatar]" />          </form>           {/* Placing the button outside the form prevents a refresh */}          <button className="button" onClick={this.onUpload}>Upload</button>        </div>      )    }  });  module.exports = User;  

User Controller:

class UsersController < ApplicationController    def update      User.find(1).update_attributes(user_params)    end      private      def user_params        params.require(:user).permit(:avatar)      end  end  

I've see that, on the web, other people used this.refs.myForm.elements so what's wrong here?

Error not raised (Rails)

Posted: 25 Jun 2016 11:47 PM PDT

I have problem with raise a error in delete method. This is my test:

context "when post state is published" do    before { post.update(state: "published", published_at: Time.current) }      it { expect { subject }.not_to change { Post.count } }    it { expect { subject }.to raise_error(PostWorkflow::InvalidStateError) }    it { is_expected.to have_http_status(422) }  end  

All tests pass except

it { expect { subject }.to raise_error(PostWorkflow::InvalidStateError) }  

In my console

expected PostWorkflow::InvalidStateError but nothing was raised  

This is my method in PostsController

def destroy    raise PostWorkflow::InvalidStateError if post.state == "published"    post.destroy!    head 200  end  

In concern ExceptionsHandler I have

included do     ...     rescue_from PostWorkflow::InvalidStateError, with: :invalid_state  end    ...    def invalid_state    render json: { error: "Invalid state" }, status: 422  end  

In PostWorkflow class I have declared error

InvalidStateError = Class.new(StandardError)  

What I did wrong?

When I try rails command I get this error

Posted: 26 Jun 2016 12:55 AM PDT

I recently tried to make a new rails project and ran 'rails new new_project' command and got this error below. Does anyone know what to do?

/usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/settings.rb:229:in scan': invalid byte sequence in US-ASCII (ArgumentError) from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/settings.rb:229:inblock in load_config' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/shared_helpers.rb:105:in filesystem_access' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/settings.rb:225:inload_config' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/settings.rb:13:in initialize' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler.rb:198:innew' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler.rb:198:in settings' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/env.rb:28:inreport' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/friendly_errors.rb:74:in request_issue_report_for' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/friendly_errors.rb:40:inlog_error' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/friendly_errors.rb:100:in rescue in with_friendly_errors' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/friendly_errors.rb:98:inwith_friendly_errors' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/exe/bundle:19:in <main>' run bundle exec spring binstub --all /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/settings.rb:229:inscan': invalid byte sequence in US-ASCII (ArgumentError) from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/settings.rb:229:in block in load_config' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/shared_helpers.rb:105:infilesystem_access' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/settings.rb:225:in load_config' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/settings.rb:13:ininitialize' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler.rb:198:in new' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler.rb:198:insettings' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/env.rb:28:in report' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/friendly_errors.rb:74:inrequest_issue_report_for' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/friendly_errors.rb:40:in log_error' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/friendly_errors.rb:100:inrescue in with_friendly_errors' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/lib/bundler/friendly_errors.rb:98:in with_friendly_errors' from /usr/local/Cellar/ruby/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.12.0.rc.3/exe/bundle:19:in'

AWS S3 403 Forbidden Error on newly created IAM inline policy for a new IAM user

Posted: 25 Jun 2016 10:53 PM PDT

I have a brand new IAM user that I want to give upload & read access to my newly created bucket - myapp.

This is the policy I am using for my user now:

{      "Version": "2012-10-17",      "Statement": [          {              "Effect": "Allow",              "Action": [                  "s3:GetBucketLocation",                  "s3:ListAllMyBuckets"              ],              "Resource": "arn:aws:s3:::*"          },          {              "Effect": "Allow",              "Action": [                  "s3:ListBucket"              ],              "Resource": [                  "arn:aws:s3:::myapp"              ]          },          {              "Effect": "Allow",              "Action": [                  "s3:PutObject",                  "s3:GetObject",                  "s3:DeleteObject"              ],              "Resource": [                  "arn:aws:s3:::myapp/*"              ]          }      ]  }  

With this policy, I can login to the console, I can create folders and I can upload images to these folders.

However, when I attempt to upload an image through my app, this is what I get:

Excon::Errors::Forbidden at /jobs  Expected(200) <=> Actual(403 Forbidden)  excon.error.response    :body          => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>0FF1D4848595DCFB</RequestId><HostId>+RrQvNFwV2hAcYPK3ZJJYzy5uiA7Aag0oc1Gpp3hENJ9lzJz453j8qJeLbdQ8jN4cc3ViRJ1lEg=</HostId></Error>"    :cookies       => [    ]    :headers       => {      "Connection"       => "close"      "Content-Type"     => "application/xml"      "Date"             => "Sat, 25 Jun 2016 18:54:24 GMT"      "Server"           => "AmazonS3"      "x-amz-id-2"       => "+R3ViRJ1lEg="      "x-amz-request-id" => "0FF1DCFB"    }    :host          => "s3.amazonaws.com"    :local_address => "192.168.1.102"    :local_port    => 23456    :path          => "/logos/company/logo/48/amped-logo.png"    :port          => 443    :reason_phrase => "Forbidden"    :remote_ip     => "xx.xx.xxx.xxx"    :status        => 403    :status_line   => "HTTP/1.1 403 Forbidden\r\n"  

Here are my CORS rules:

<?xml version="1.0" encoding="UTF-8"?>  <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">      <CORSRule>          <AllowedOrigin>http://localhost:3000</AllowedOrigin>          <AllowedMethod>HEAD</AllowedMethod>          <AllowedMethod>GET</AllowedMethod>          <AllowedMethod>PUT</AllowedMethod>          <AllowedMethod>POST</AllowedMethod>          <AllowedMethod>DELETE</AllowedMethod>          <ExposeHeader>ETag</ExposeHeader>          <AllowedHeader>*</AllowedHeader>      </CORSRule>  </CORSConfiguration>  

This is my config/initializers/carrierwave.rb file:

CarrierWave.configure do |config|    config.fog_credentials = {      provider:               'AWS',      aws_access_key_id:      ENV["MYAPP_S3_KEY"],      aws_secret_access_key: ENV["MYAPP_SECRET_KEY"]    }    config.fog_directory  = ENV["MYBUCKET"]  end  

What could be causing this and how do I fix it?

Rails query changes the time

Posted: 25 Jun 2016 10:46 PM PDT

<% date = Time.now.beginning_of_day %>  <%= date %> prints 2016-06-01 00:00:00 +0600  <% schedule = Schedule.where(:date_ => date).first %>  <%= date %> prints 2016-05-31 18:00:00 UTC  

2016-06-01 00:00:00 +0600

2016-05-31 18:00:00 UTC

Using mongoid

date_ is Time field

My local timezone is UTC +6

I am sorry if my question is stupid -_-'

Unpermitted parameter error - Devise + Paperclip + Heroku + S3

Posted: 25 Jun 2016 10:00 PM PDT

I could really use some help on getting a profile image to upload correctly to S3 via an application I've built using Devise for users and Paperclip for the image upload.

My other models are all working great with Paperclip thru Heroku to S3, the only model I can't get working is the User model from Devise. I've read a 100 different articles on setting up configured permitted parameters for devise and no variable seems to work. I've read all the Stack Overflow Q&A's on this issue and none seem to relate to mine.

I added other attributes to the user model (profile name, dob, etc.) and all of those attributes are working just fine. Only the image is not working.

I've included below the complete log file that shows the Error Message - "Unpermitted Parameter: polaroid."

Paperclip 'image' file name is called 'Polaroid'.

Any thoughts?? thanks!

Application Controller.rb

     class ApplicationController < ActionController::Base        # Prevent CSRF attacks by raising an exception.        # For APIs, you may want to use :null_session instead.          protect_from_forgery with: :exception              before_filter :configure_permitted_parameters, if: :devise_controller?            protected            def configure_permitted_parameters              devise_parameter_sanitizer.for(:account_update).push(:email, :password, :current_password, :password_confirmation, :profile_name, :profile_dob, :profile_zipcode, :profile_country, :profile_timezone, :profile_datejoined, :profile_occupation, :profile_school, :profile_biography, :filter_dateyesno, :filter_distancefrom, :filter_organizerage_min, :filter_organizerage_max, :filter_groupsize_min, :filter_groupsize_max, :profile_gender, :polaroid)              devise_parameter_sanitizer.for(:sign_up).push(:email, :password, :password_confirmation, :profile_name, :profile_dob, :profile_zipcode, :profile_country, :profile_timezone, :profile_datejoined, :profile_occupation, :profile_school, :profile_biography, :filter_dateyesno, :filter_distancefrom, :filter_organizerage_min, :filter_organizerage_max, :filter_groupsize_min, :filter_groupsize_max, :profile_gender, :polaroid)          end          end  

Users Controller.rb

class UsersController < ApplicationController          def index              @users = User.all          end             def show              @user = User.find(params[:id])          end             private              def user_params                  params.require(:user).permit(:email, :password, :current_password, :password_confirmation, :profile_name, :profile_dob, :profile_zipcode, :profile_country, :profile_timezone, :profile_datejoined, :profile_occupation, :profile_school, :profile_biography, :filter_dateyesno, :filter_distancefrom, :filter_organizerage_min, :filter_organizerage_max, :filter_groupsize_min, :filter_groupsize_max, :profile_gender, :polaroid)              end        end  

Edit.html.erb from Devise Registration

<h2>Update Profile Information</h2>    <%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>    <%= f.error_notification %>        <div class="field">        <%= f.label :email %><br />        <%= f.email_field :email, autofocus: true %>      </div>        <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %>        <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div>      <% end %>        <% if current_user.polaroid.exists? %>        <%= image_tag (current_user.polaroid.url(:small)) %><br/>        <%= f.file_field :polaroid, multiple: true %>      <% else %>        <div class="field">          <%= f.label :profile_photo %>          <%= f.file_field :polaroid, multiple: true %>        </div>      <% end %>        <div class="field">        <%= f.label :first_name %><br />        <%= f.text_field :profile_name, autofocus: true %>      </div>        <div class="field">        <%= f.label :birthday %><br />        <%= f.date_field :profile_dob, autofocus: true %>      </div>      <div class="field">        <%= f.label :gender %><br />        <%= f.text_field :profile_gender, autofocus: true %>      </div>      <div class="field">        <%= f.label :zipcode %><br />        <%= f.text_field :profile_zipcode, autofocus: true %>      </div>        <div class="field">        <%= f.label :country %><br />        <%= f.text_field :profile_country, autofocus: true %>      </div>        <div class="field">        <%= f.label :timezone %><br />        <%= f.text_field :profile_timezone, autofocus: true %>      </div>        <div class="field">        <%= f.label :occupation %><br />        <%= f.text_field :profile_occupation, autofocus: true %>      </div>        <div class="field">        <%= f.label :university_attended %><br />        <%= f.text_field :profile_school, autofocus: true %>      </div>        <div class="field">        <%= f.label :biography %><br />        <%= f.text_field :profile_biography, autofocus: true %>      </div>      <br />      <%= f.input :filter_dateyesno, label: "Are you single and looking for dates?", as: :radio_buttons %>      <br />        <div class="field">        <%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />        <%= f.password_field :current_password, autocomplete: "off" %>      </div>        <div class="field">        <%= f.label :new_password %> <i>(leave blank if you don't want to change it)</i><br />        <%= f.password_field :password, autocomplete: "off" %>      </div>        <div class="field">        <%= f.label :new_password_confirmation %><br />        <%= f.password_field :password_confirmation, autocomplete: "off" %>      </div>        <br />      <h4>Make sure to type in your password before updating</h4>    <%= f.button :submit, "Update" %>    <% end %>    <h3>Cancel my account</h3>    <p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p>    <%= link_to "Back", :back %>  

Other Paperclip Model that is working:

        Started POST "/outings" for ::1 at 2016-06-25 20:47:39 -0400      Processing by OutingsController#create as HTML          Parameters: {"utf8"=>"✓", "authenticity_token"=>"/eflxdhQ1vPTnTE1YnCOes0k6iggGE64oSI6LDhyRepODp3FZ6FDIaxBVZEZCPge2gHQaHZjjLPhHsUh1IWY6g==",         "outing"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fc792c98bf8       @tempfile=#<Tempfile:/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/RackMultipart20160625-38562-t3pccn.png>,       @original_filename="Beer.png",       @content_type="image/png",       @headers="Content-Disposition: form-data; name=\"outing[image]\";       filename=\"Beer.png\"\r\nContent-Type: image/png\r\n">,         "date_date(1i)"=>"2016", "date_date(2i)"=>"6", "date_date(3i)"=>"28", "date_time(1i)"=>"2016", "date_time(2i)"=>"6", "date_time(3i)"=>"26", "date_time(4i)"=>"00", "date_time(5i)"=>"47", "date_duration"=>"2", "date_title"=>"Beer Garden", "date_category"=>"Drinking", "date_description"=>"Beer Garden", "date_location"=>"New York", "date_city"=>"", "date_state"=>"", "date_zip"=>""}, "commit"=>"Create New Date"}        User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1  ORDER BY "users"."id" ASC LIMIT 1  [["id", 20]]      Command :: file -b --mime '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-40htqc.png'      Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]' 2>/dev/null      Command :: identify -format %m '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]'      Command :: convert '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]' -auto-orient -resize "x600" -crop "600x600+11+0" +repage '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/4331dbefbe38c7e67b6851de8064954e20160625-38562-1ljzx69'      Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]' 2>/dev/null      Command :: identify -format %m '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]'      Command :: convert '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]' -auto-orient -resize "x300" -crop "300x300+5+0" +repage '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/4331dbefbe38c7e67b6851de8064954e20160625-38562-1pw6qi3'      Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]' 2>/dev/null      Command :: identify -format %m '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]'      Command :: convert '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]' -auto-orient -resize "x150" -crop "150x150+2+0" +repage '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/4331dbefbe38c7e67b6851de8064954e20160625-38562-16rm0mr'      Command :: identify -format '%wx%h,%[exif:orientation]' '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]' 2>/dev/null      Command :: identify -format %m '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]'      Command :: convert '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-1ep7wo7.png[0]' -auto-orient -resize "x50" -crop "50x50+0+0" +repage '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/4331dbefbe38c7e67b6851de8064954e20160625-38562-ge9nrr'         (0.3ms)  BEGIN      Command :: file -b --mime '/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/c6884357e49fd6b1fdede867c96aafb120160625-38562-we9bgq.png'        SQL (0.5ms)  INSERT INTO "outings" ("date_title", "date_description", "date_duration", "date_category", "date_location", "date_city", "date_state", "image_file_name", "image_content_type", "image_file_size", "image_updated_at", "date_date", "date_time", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) RETURNING "id"  [["date_title", "Beer Garden"], ["date_description", "Beer Garden"], ["date_duration", 2], ["date_category", "Drinking"], ["date_location", "New York"], ["date_city", ""], ["date_state", ""], ["image_file_name", "Beer.png"], ["image_content_type", "image/png"], ["image_file_size", 520764], ["image_updated_at", "2016-06-25 20:47:39.380829"], ["date_date", "2016-06-28"], ["date_time", "2016-06-26 00:47:00.000000"], ["user_id", 20], ["created_at", "2016-06-25 20:47:39.961401"], ["updated_at", "2016-06-25 20:47:39.961401"]]      [paperclip] saving /outings/images/000/000/017/original/Beer.png      [paperclip] saving /outings/images/000/000/017/large/Beer.png      [paperclip] saving /outings/images/000/000/017/medium/Beer.png      [paperclip] saving /outings/images/000/000/017/small/Beer.png      [paperclip] saving /outings/images/000/000/017/thumb/Beer.png         (6.4ms)  COMMIT      Redirected to http://localhost:3000/outings/17      Completed 302 Found in 2514ms (ActiveRecord: 7.5ms)  

Error Message - Unpermitted Parameter: polaroid

Started POST "/users" for ::1 at 2016-06-25 20:43:38 -0400      Processing by Devise::RegistrationsController#create as HTML          Parameters: {"utf8"=>"✓", "authenticity_token"=>"tNW/ks6w12sLo3T8RBaZhQMBbRyddmdEh6K386BGfwoHPMeScUFCuXR/EFg/bu/hFCRXXMsNpU/Hnkj+TLGiCg==", "user"=>{"email"=>"testjun25v3@testing.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]",         "polaroid"=>#<ActionDispatch::Http::UploadedFile:0x007fc78f08bf48 @tempfile=#<Tempfile:/var/folders/00/cvfs5p4964q5q3lq115svtf00000gn/T/RackMultipart20160625-38562-1obgcrh.png>, @original_filename="jazz.png",       @content_type="image/png",       @headers="Content-Disposition: form-data; name=\"user[polaroid]\";       filename=\"jazz.png\"\r\nContent-Type: image/png\r\n">,         "profile_name"=>"Jazz Man", "profile_dob"=>"", "profile_gender"=>"", "profile_zipcode"=>"", "profile_country"=>"", "profile_timezone"=>"", "profile_occupation"=>"", "profile_school"=>"", "profile_biography"=>"Jazz Lover"}, "commit"=>"Sign up"}        Unpermitted parameter: polaroid           (0.2ms)  BEGIN        User Exists (0.3ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = 'testjun25v3@testing.com' LIMIT 1        SQL (0.4ms)  INSERT INTO "users" ("email", "encrypted_password", "profile_name", "profile_gender", "profile_country", "profile_timezone", "profile_occupation", "profile_school", "profile_biography", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING "id"  [["email", "testjun25v3@testing.com"], ["encrypted_password", "$2a$10$TNIGv9c3GUh8RR.qvMv6eubGd6kgoA6aUeGichYzXWhRYF1QoFvgS"], ["profile_name", "Jazz Man"], ["profile_gender", ""], ["profile_country", ""], ["profile_timezone", ""], ["profile_occupation", ""], ["profile_school", ""], ["profile_biography", "Jazz Lover"], ["created_at", "2016-06-25 20:43:38.367890"], ["updated_at", "2016-06-25 20:43:38.367890"]]         (1.1ms)  COMMIT         (0.2ms)  BEGIN        SQL (0.4ms)  UPDATE "users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "last_sign_in_ip" = $3, "current_sign_in_ip" = $4, "sign_in_count" = $5, "updated_at" = $6 WHERE "users"."id" = $7  [["last_sign_in_at", "2016-06-25 20:43:38.371506"], ["current_sign_in_at", "2016-06-25 20:43:38.371506"], ["last_sign_in_ip", "::1/128"], ["current_sign_in_ip", "::1/128"], ["sign_in_count", 1], ["updated_at", "2016-06-25 20:43:38.372369"], ["id", 20]]         (0.3ms)  COMMIT      Redirected to http://localhost:3000/      Completed 302 Found in 78ms (ActiveRecord: 2.9ms)  

User Model

class User < ActiveRecord::Base    # Include default devise modules. Others available are:    # :confirmable, :lockable, :timeoutable and :omniauthable    devise :database_authenticatable, :registerable,           :recoverable, :rememberable, :trackable, :validatable    has_many :clubs    has_many :outings    has_many :events    has_many :activities    has_many :uploads      has_attached_file :polaroid, styles: { large: "600x600#", medium: "300x300#", small: "150x150#", thumb: "50x50#" }, default_url: "/images/:style/missing.png"    validates_attachment_content_type :polaroid, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png"]  end  

Google Maps API get a printout of a county?

Posted: 25 Jun 2016 08:47 PM PDT

I'm curious, is there a way to use Google Maps API to request an image of a map? Here is what I want to do. I have a Rails app. I'm creating a bunch of users with random zip codes/ addresses. I want to send Google the county name and download or capture the image of the map for the user's profile pic. Is that doable? :)

Converting integer to star rating

Posted: 25 Jun 2016 09:15 PM PDT

Firstly here is my file structure

application_helper.rb

module ApplicationHelper    def show_stars(review)      image_tag review.rating    end  end  

Controller: customers_controller.rb

class CustomersController < ApplicationController    before_action :require_admin    # reviews    def reviews      @reviews = Review.all    end  end  

view: reviews.haml

%table.table.table-striped    %thead      %tr        %th{ :style => "width:8%" } Ratings        %tbody          - @reviews.each do |review|            %tr              %td{ :style => "text-align:center" }= review.rating.show_stars  

I have rating setup as a integer in my schema and what I am trying to do is convert the integer into a star image via the application helper. However when i try using my method i end up getting

undefined method `show_stars' for 4:Fixnum // 4 is my rating value  

What am I missing here? I'm just starting out on ruby so any advice is appreciated.

No comments:

Post a Comment