Showing posts with label ruby-on-rails-4. Show all posts
Showing posts with label ruby-on-rails-4. Show all posts

Wednesday, May 23, 2018

Parse 'ul' and 'ol' tags

Leave a Comment

I have to handle deep nesting of ul, ol, and li tags. I need to give the same view as we are giving in the browser. I want to achieve the following example in a pdf file:

 text = " <body>     <ol>         <li>One</li>         <li>Two              <ol>                 <li>Inner One</li>                 <li>inner Two                      <ul>                         <li>hey                              <ol>                                 <li>hiiiiiiiii</li>                                 <li>why</li>                                 <li>hiiiiiiiii</li>                             </ol>                         </li>                         <li>aniket </li>                     </li>                 </ul>                 <li>sup </li>                 <li>there </li>             </ol>             <li>hey </li>             <li>Three</li>         </li>     </ol>     <ol>         <li>Introduction</li>         <ol>             <li>Introduction</li>         </ol>         <li>Description</li>         <li>Observation</li>         <li>Results</li>         <li>Summary</li>     </ol>     <ul>         <li>Introduction</li>         <li>Description              <ul>                 <li>Observation                      <ul>                         <li>Results                              <ul>                                 <li>Summary</li>                             </ul>                         </li>                     </ul>                 </li>             </ul>         </li>         <li>Overview</li>     </ul> </body>" 

I have to use prawn for my task. But prawn doesn't support HTML tags. So, I came up with a solution using nokogiri:. I am parsing and later removing the tags with gsub. The below solution I have written for a part of the above content but the problem is ul and ol can vary.

     RULES = {   ol: {     1 => ->(index) { "#{index + 1}. " },     2 => ->(index) { "#{}" },     3 => ->(index) { "#{}" },     4 => ->(index) { "#{}" }   },   ul: {     1 => ->(_) { "\u2022 " },     2 => ->(_) { "" },     3 => ->(_) { "" },     4 => ->(_) { "" },   } }  def ol_rule(group, deepness: 1)   group.search('> li').each_with_index do |item, i|     prefix = RULES[:ol][deepness].call(i)     item.prepend_child(prefix)     descend(item, deepness + 1)   end end  def ul_rule(group, deepness: 1)   group.search('> li').each_with_index do |item, i|     prefix = RULES[:ul][deepness].call(i)     item.prepend_child(prefix)     descend(item, deepness + 1)   end end  def descend(item, deepness)   item.search('> ol').each do |ol|     ol_rule(ol, deepness: deepness)   end   item.search('> ul').each do |ul|     ul_rule(ul, deepness: deepness)   end end  doc = Nokogiri::HTML.fragment(text)  doc.search('ol').each do |group|   ol_rule(group, deepness: 1) end  doc.search('ul').each do |group|   ul_rule(group, deepness: 1) end     puts doc.inner_text   1. One 2. Two  1. Inner One 2. inner Two  • hey  1. hiiiiiiiii 2. why 3. hiiiiiiiii   • aniket    3. sup  4. there   3. hey  4. Three    1. Introduction  1. Introduction  2. Description 3. Observation 4. Results 5. Summary    • Introduction • Description  • Observation  • Results  • Summary       • Overview 

Problem

1) What I want to achieve is how to handle space when working with ul and ol tags
2) How to handle deep nesting when li come inside ul or li come inside ol

2 Answers

Answers 1

I've come up with a solution that handles multiple identations with configurable numeration rules per level:

require 'nokogiri' ROMANS = %w[i ii iii iv v vi vii viii ix]  RULES = {   ol: {     1 => ->(index) { "#{index + 1}. " },     2 => ->(index) { "#{('a'..'z').to_a[index]}. " },     3 => ->(index) { "#{ROMANS.to_a[index]}. " },     4 => ->(index) { "#{ROMANS.to_a[index].upcase}. " }   },   ul: {     1 => ->(_) { "\u2022 " },     2 => ->(_) { "\u25E6 " },     3 => ->(_) { "* " },     4 => ->(_) { "- " },   } }  def ol_rule(group, deepness: 1)   group.search('> li').each_with_index do |item, i|     prefix = RULES[:ol][deepness].call(i)     item.prepend_child(prefix)     descend(item, deepness + 1)   end end  def ul_rule(group, deepness: 1)   group.search('> li').each_with_index do |item, i|     prefix = RULES[:ul][deepness].call(i)     item.prepend_child(prefix)     descend(item, deepness + 1)   end end  def descend(item, deepness)   item.search('> ol').each do |ol|     ol_rule(ol, deepness: deepness)   end   item.search('> ul').each do |ul|     ul_rule(ul, deepness: deepness)   end end  doc = Nokogiri::HTML.fragment(text)  doc.search('ol:root').each do |group|   binding.pry   ol_rule(group, deepness: 1) end  doc.search('ul:root').each do |group|   ul_rule(group, deepness: 1) end 

You can then remove the tags or use doc.inner_text depending on your environment.

Two caveats though:

  1. Your entry selector must be carefully selected. I used your snippet verbatim without root element, thus i had to use ul:root/ol:root. Maybe "body > ol" works for your situation too. Maybe selecting each ol/ul but than walking each and only find those, that have no list parent.
  2. Using your example verbatim, Nokogiri does not handle the last 2 list items of the first group ol very well ("hey", "Three") When parsing with nokogiri, thus elements already "left" their ol tree and got placed in the root tree.

Current Output:

  1. One   2. Two       a. Inner One       b. inner Two         ◦ hey         ◦ hey       3. hey       4. hey   hey   Three    1. Introduction     a. Introduction   2. Description   3. Observation   4. Results   5. Summary    • Introduction   • Description       ◦ Observation           * Results               - Summary   • Overview 

Answers 2

Whenever you are in a ol, li or ul element, you must recursively check for ol, li and ul. If there are none of them, return (what have been discovered as a substructure), if there are, call the same function on the new node and add its return value to the current structure.

You perform a different action on each node no matter where it is depending on its type and then the function automatically repackage everything.

Read More

Wednesday, February 7, 2018

Rails: eager-loading on an already-left-joined table?

Leave a Comment

We are already left-joining a table so that we can order by a column, if the relation exists:

people = Person   .joins("LEFT JOIN addresses ON addresses.id = people.address_id")   .order("addresses.country")   .all 

This results in a single SQL query, but I'd like to have people.first.address not trigger SQL to load the address. I am left-joining because some people don't have addresses.

.includes(:address) triggers a separate query.

You can do what I'm suggesting with inner joins, using includes, but that triggers 2 SQL queries:

Person.includes(:address).all 

While joins + includes triggers only one (but INNER joins):

Person.joins(:address).includes(:address).all 

Active record also uses left joins if you force a join while eager-loading .eager_load(:addresses).

Can you take an existing left-join and have rails eager-load with those results? So far I can't find this.

3 Answers

Answers 1

Well, in your case you could select your query creating an alias for the fields you are going to use from address something like this:

people = Person          .joins("LEFT JOIN addresses ON addresses.id = people.address_id")          .select("people.*, addresses.country as address_country")          .order("address_country")          .all 

This won't change your desired query and will not result in extra queries, not for country at least.

Answers 2

Try this:

people = Person.   eager_load(:address).   merge(Address.order("coalesce(country, '')")).   all  people.first.address 

eager_load forces eager loading by performing a LEFT OUTER JOIN.

I added a coalesce on country so you have more control over where people without addresses appear in the results.

Here is what it looks like for me:

people = Person.   eager_load(:address).   merge(Address.order("coalesce(country, '')")).   all  (0.5ms)  SELECT DISTINCT COUNT(DISTINCT "people"."id") FROM "people" LEFT OUTER JOIN "addresses" ON "addresses"."person_id" = "people"."id" SQL (2.1ms)  SELECT "people"."id" AS t0_r0, "people"."name" AS t0_r1, "people"."created_at" AS t0_r2, "people"."updated_at" AS t0_r3, "addresses"."id" AS t1_r0, "addresses"."person_id" AS t1_r1, "addresses"."address" AS t1_r2, "addresses"."country" AS t1_r3, "addresses"."created_at" AS t1_r4, "addresses"."updated_at" AS t1_r5 FROM "people" LEFT OUTER JOIN "addresses" ON "addresses"."person_id" = "people"."id" ORDER BY coalesce(addresses.country, '')   people.first.address nil  people.last.address #<Address:0x007febabb508a8> {             :id => 1,      :person_id => 4,        :address => "24175 Gerhold Prairie",        :country => "O",     :created_at => Thu, 01 Feb 2018 18:47:45 UTC +00:00,     :updated_at => Thu, 01 Feb 2018 18:47:45 UTC +00:00 } 

Note that no queries are run when you access the addresses

I'll point that you've ordered by a table that left outer joined, so you need to decide how you want to treat nulls.

Answers 3

You can uses #references with #includes to LEFT JOIN your relation and achieve what you are after.

people = Person   .includes(:addresses)   .references(:addresses)   .order("addresses.country") 

This will yield one query and all the people, whether or not they have an address, and also eager load the addresses to avoid the dreaded N + 1 queries.

The documentation doesn't do a great job of explaining that #references will add a LEFT JOIN but it's purpose is to allow adding SQL clauses (WHERE, ORDER, GROUP, etc.) on the relation in conjunction with #includes.

Read More

Tuesday, December 19, 2017

Multi-Table Invoice SUM Comparison

Leave a Comment

Say I have 3 tables in a rails app:

invoices

id  | customer_id  | employee_id  | notes --------------------------------------------------------------- 1   | 1            | 5            | An order with 2 items. 2   | 12           | 5            | An order with 1 item. 3   | 17           | 12           | An empty order. 4   | 17           | 12           | A brand new order. 

invoice_items

id  | invoice_id  | price  | name --------------------------------------------------------- 1   | 1           | 5.35   | widget 2   | 1           | 7.25   | thingy 3   | 2           | 1.25   | smaller thingy 4   | 2           | 1.25   | another smaller thingy 

invoice_payments

id  | invoice_id  | amount  | method      | notes --------------------------------------------------------- 1   | 1           | 4.85    | credit card | Not enough  2   | 1           | 1.25    | credit card | Still not enough 3   | 2           | 1.25    | check       | Paid in full 

This represents 4 orders:

The first has 2 items, for a total of 12.60. It has two payments, for a total paid amount of 6.10. This order is partially paid.

The second has only one item, and one payment, both totaling 1.25. This order is paid in full.

The third order has no items or payments. This is important to us, sometimes we use this case. It is considered paid in full as well.

The final order has one item again, for a total of 1.25, but no payments as of yet.

Now I need a query:

Show me all orders that are not paid in full yet; that is, all orders such that the total of the items is greater than the total of the payments.

I can do it in pure sql:

SELECT      invoices.*,             invoice_payment_amounts.amount_paid AS amount_paid,             invoice_item_amounts.total_amount AS total_amount FROM        invoices LEFT JOIN   (                 SELECT      invoices.id AS invoice_id,                             COALESCE(SUM(invoice_payments.amount), 0) AS amount_paid                 FROM        invoices                 LEFT JOIN   invoice_payments                 ON          invoices.id = invoice_payments.invoice_id                 GROUP BY    invoices.id             ) AS invoice_payment_amounts ON          invoices.id = invoice_payment_amounts.invoice_id LEFT JOIN   (                 SELECT      invoices.id AS invoice_id,                             COALESCE(SUM(invoice_items.item_price), 0) AS total_amount                 FROM        invoices                 LEFT JOIN   invoice_items                 ON          invoices.id = invoice_items.invoice_id                 GROUP BY    invoices.id             ) AS invoice_item_amounts ON          invoices.id = invoice_item_amounts.invoice_id WHERE       amount_paid < total_amount 

But...now I need to get that into rails (probably as a scope). I can use find_by_sql, but that then returns an array, rather than an ActiveRecord::Relation, which is not what I need, since I want to chain it with other scopes (there is, for example, an overdue scope, which uses this), etc.

So raw SQL probably isn't the right way to go here.....but what is? I've not been able to do this in activerecord's query language.

The closest I've gotten so far was this:

Invoice.select('invoices.*, SUM(invoice_items.price) AS total, SUM(invoice_payments.amount) AS amount_paid').   joins(:invoice_payments, :invoice_items).   group('invoices.id').   where('amount_paid < total') 

But that fails, since on orders like #1, with multiple payments, it incorrectly doubles the price of the order (due to multiple joins), showing it as still unpaid. I had the same problem in SQL, which is why I structured it in the way I did.

Any thoughts here?

2 Answers

Answers 1

You can get your results using group by and having clause of MySQL as:

Pure MySQL Query:

  SELECT `invoices`.* FROM `invoices`    INNER JOIN `invoice_items` ON      `invoice_items`.`invoice_id` = `invoices`.`id`    INNER JOIN `invoice_payments` ON      `invoice_payments`.`invoice_id` = `invoices`.`id`    GROUP BY invoices.id      HAVING sum(invoice_items.price) < sum(invoice_payments.amount)  

ActiveRecord Query:

Invoice.joins(:invoice_items, :invoice_payments).group("invoices.id").having("sum(invoice_items.price) < sum(:invoice_payments.amount)") 

Answers 2

When building more complex queries in Rails usually Arel Really Exasperates Logicians comes in handy

Arel is a SQL AST manager for Ruby. It

  1. simplifies the generation of complex SQL queries, and
  2. adapts to various RDBMSes.

Here is a sample how the Arel implementation would look like based on the requirements

invoice_table = Invoice.arel_table  # Define invoice_payment_amounts payment_arel_table = InvoicePayment.arel_table invoice_payment_amounts = Arel::Table.new(:invoice_payment_amounts) payment_cte = Arel::Nodes::As.new(   invoice_payment_amounts,   payment_arel_table     .project(payment_arel_table[:invoice_id],              payment_arel_table[:amount].sum.as("amount_paid"))     .group(payment_arel_table[:invoice_id]) )  # Define invoice_item_amounts item_arel_table = InvoiceItem.arel_table invoice_item_amounts =  Arel::Table.new(:invoice_item_amounts) item_cte = Arel::Nodes::As.new(   invoice_item_amounts,   item_arel_table     .project(item_arel_table[:invoice_id],              item_arel_table[:price].sum.as("total"))     .group(item_arel_table[:invoice_id]) )  # Define main query query = invoice_table           .project(             invoice_table[Arel.sql('*')],             invoice_payment_amounts[:amount_paid],             invoice_item_amounts[:total]           )           .join(invoice_payment_amounts).on(             invoice_table[:id].eq(invoice_payment_amounts[:invoice_id])           )           .join(invoice_item_amounts).on(             invoice_table[:id].eq(invoice_item_amounts[:invoice_id])           )           .where(invoice_item_amounts[:total].gt(invoice_payment_amounts[:amount_paid]))           .with(payment_cte, item_cte)   res = Invoice.find_by_sql(query.to_sql) for r in res do   puts "---- Invoice #{r.id} -----"   p r   puts "total: #{r[:total]}"   puts "amount_paid: #{r[:amount_paid]}"   puts "----" end 

This will return the same output as your SQL query using the sample data you have provided to the question. Output:

 <Invoice id: 2, notes: "An order with 1 items.", created_at: "2017-12-18 21:15:47", updated_at: "2017-12-18 21:15:47">  total: 2.5  amount_paid: 1.25  ----  ---- Invoice 1 -----  <Invoice id: 1, notes: "An order with 2 items.", created_at: "2017-12-18 21:15:47", updated_at: "2017-12-18 21:15:47">  total: 12.6  amount_paid: 6.1  ---- 

Arel is quite flexible so you can use this as a base and refine the query conditions based on more specific requirements you might have.

I would strongly recommend for you to consider creating a cache columns (total, amount_paid) in the Invoice table and maintain them so you can avoid this complex query. At least the total additional column would be quite simple to create and fill the data.

Read More

Wednesday, September 27, 2017

Why do I get invalid byte sequence in UTF-8

Leave a Comment

Why do I get this error ?

invalid byte sequence in UTF-8 

for loading an image in:

= image_tag 'features_home/show1.png' 

EDIT

I've notice that this issue occurred only after I did bundle update, the error occurs with any image.. I will try to add details here:

Stacktrace:

  Rendered home/home.html.haml within layouts/application (229.9ms) Completed 500 Internal Server Error in 1047ms invalid byte sequence in UTF-8 excluded from capture: DSN not set  ActionView::Template::Error (invalid byte sequence in UTF-8):     81:           / Carousel items     82:           .carousel-inner     83:             .active.item     84:               = image_tag 'features_home/show1.png'     85:               -#.carousel-caption     86:               -#  %h4     87:               -#  %p   app/views/home/home.html.haml:84:in `block in _app_views_home_home_html_haml__623651309533727079_70331260863620'   app/views/home/home.html.haml:33:in `_app_views_home_home_html_haml__623651309533727079_70331260863620'   lib/rack/seoredirect.rb:20:in `call'     Rendered /Users/Apple/.rvm/gems/ruby-2.2.2@myapp/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (115.6ms)   Rendered /Users/Apple/.rvm/gems/ruby-2.2.2@myapp/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (23.1ms)   Rendered /Users/Apple/.rvm/gems/ruby-2.2.2@myapp/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.7ms)   Rendered /Users/Apple/.rvm/gems/ruby-2.2.2@myapp/gems/actionpack-4.2.0/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (237.9ms) 

Gemfile.lock before and after bundle update: https://gist.github.com/hopewise/35c2a98b13ac646b65770feb2f3c7ec8

Full trace: https://gist.github.com/hopewise/551169518a5938647dc767d3de393cd4

I don't know which gem caused the issue though..

0 Answers

Read More

Tuesday, August 8, 2017

select all records holding some condition in has_many association - Ruby On Rails

Leave a Comment

I have a model profile.rb with following association

class User < ActiveRecord::Base    has_one :profile end  class Profile < ActiveRecord::Base     has_many :skills     belongs_to :user end 

I have a model skills.rb with following association

class Skill < ActiveRecord::Base     belongs_to :profile end 

I have following entries in skills table

id:         name:           profile_id: ==================================================== 1           accounting          1 2           martial arts        2 3           law                 1 4           accounting          2 5           journalist          3 6           administration      1 

and so on , how can i query all the profiles with ,lets say, "accounting" & "administration" skills which will be profile with id 1 considering the above recode. so far i have tried following

Profile.includes(:skills).where(skills: {name: ["accounting" , "administration"]} ) 

but instead of finding profile with id 1 - It gets me [ 1, 2 ] because profile with id 2 holds "accounting" skills and it's performing an "IN" operation in database

Note: I'm using postgresql and question is not only about a specific id of profile as described (which i used only as an example) - The original question is to get all the profiles which contain these two mentioned skills.

My activerecord join fires the following query in postgres

SELECT FROM "profiles" LEFT OUTER JOIN "skills" ON "skills"."profile_id" = "profiles"."id" WHERE "skills"."name" IN ('Accounting', 'Administration') 

In below Vijay Agrawal's answer is something which i already have in my application and both, his and mine, query use IN wildcard which result in profile ids which contain either of skills while my question is to get profile ids which contain both the skills. I'm sure that there must be a way to fix this thing in the same query way which is listed in original question and i'm curious to learn that way . I hope that i'll get some more help with you guys - thanks

For clarity, I want to query all the profiles with multiple skills in a model with has_many relationship with profile model - using the Profile as primary table not the skills

Reason for using Profile as primary table is that in pagination i don't want to get all skills from related table ,say 20_000 or more rows and then filter according to profile.state column . instead anyone would like to select only 5 records which meet the profile.state , profile.user.is_active and other columns condition and match the skills without retrieving thousands of irrelevant records and then filter them again.

5 Answers

Answers 1

You should do this to get all profile_ids which have both accounting and administration skills :

Skill.where(name: ["accounting", "administration"]).group(:profile_id).having("count('id') = 2").pluck(:profile_id) 

If you need profiles details, you can put this query in where clause of Profile for id.

Note the number 2 in query, it is length of your array used in where clause. In this case ["accounting", "administration"].length

UPDATE::

Based on updated question description, instead of pluck you can use select and add subquery to make sure it happens in one query.

Profile.where(id: Skill.where(name: ["accounting", "administration"]).group(:profile_id).having("count('id') = 2").select(:profile_id)) 

More over you have control over sorting, pagination and additional where clause. Don't see any concerns over there which are mentioned in question edit.

UPDATE 2::

Another way to get intersect of profiles with both the skills (likely to be less efficient than above solution):

profiles = Profile  ["accounting", "administration"].each do |name|   profiles = profiles.where(id: Skill.where(name: name).select(:profile_id)) end 

Answers 2

Profile.includes(:skills).where("skills.name" => %w(accounting administration)) 

For more information, read about finding through ActiveRecord associations.

Update

If this is not working for you then you likely do not have your database and models properly configured, because in a brand new Rails app this works as expected.

class CreateProfiles < ActiveRecord::Migration[5.1]   def change     create_table :profiles do |t|       t.timestamps     end   end end  class CreateSkills < ActiveRecord::Migration[5.1]   def change     create_table :skills do |t|       t.string :name       t.integer :profile_id       t.timestamps     end   end end  class Profile < ApplicationRecord   has_many :skills end  class Skill < ApplicationRecord   belongs_to :profile end  Profile.create Profile.create Skill.create(name: 'foo', profile_id: 1) Skill.create(name: 'bar', profile_id: 1) Skill.create(name: 'baz', profile_id: 2)  Profile.includes(:skills).where("skills.name" => %w(foo))   SQL (0.3ms)  SELECT  DISTINCT "profiles"."id" FROM "profiles" LEFT OUTER JOIN "skills" ON "skills"."profile_id" = "profiles"."id" WHERE "skills"."name" = 'foo' LIMIT ?  [["LIMIT", 11]]   SQL (0.1ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."created_at" AS t0_r1, "profiles"."updated_at" AS t0_r2, "skills"."id" AS t1_r0, "skills"."name" AS t1_r1, "skills"."profile_id" AS t1_r2, "skills"."created_at" AS t1_r3, "skills"."updated_at" AS t1_r4 FROM "profiles" LEFT OUTER JOIN "skills" ON "skills"."profile_id" = "profiles"."id" WHERE "skills"."name" = 'foo' AND "profiles"."id" = 1  => #<ActiveRecord::Relation [#<Profile id: 1, created_at: "2017-07-28 21:52:56", updated_at: "2017-07-28 21:52:56">]>  Profile.includes(:skills).where("skills.name" => %w(bar))   SQL (0.3ms)  SELECT  DISTINCT "profiles"."id" FROM "profiles" LEFT OUTER JOIN "skills" ON "skills"."profile_id" = "profiles"."id" WHERE "skills"."name" = 'bar' LIMIT ?  [["LIMIT", 11]]   SQL (0.1ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."created_at" AS t0_r1, "profiles"."updated_at" AS t0_r2, "skills"."id" AS t1_r0, "skills"."name" AS t1_r1, "skills"."profile_id" AS t1_r2, "skills"."created_at" AS t1_r3, "skills"."updated_at" AS t1_r4 FROM "profiles" LEFT OUTER JOIN "skills" ON "skills"."profile_id" = "profiles"."id" WHERE "skills"."name" = 'bar' AND "profiles"."id" = 1  => #<ActiveRecord::Relation [#<Profile id: 1, created_at: "2017-07-28 21:52:56", updated_at: "2017-07-28 21:52:56">]>  Profile.includes(:skills).where("skills.name" => %w(baz))   SQL (0.3ms)  SELECT  DISTINCT "profiles"."id" FROM "profiles" LEFT OUTER JOIN "skills" ON "skills"."profile_id" = "profiles"."id" WHERE "skills"."name" = 'baz' LIMIT ?  [["LIMIT", 11]]   SQL (0.1ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."created_at" AS t0_r1, "profiles"."updated_at" AS t0_r2, "skills"."id" AS t1_r0, "skills"."name" AS t1_r1, "skills"."profile_id" AS t1_r2, "skills"."created_at" AS t1_r3, "skills"."updated_at" AS t1_r4 FROM "profiles" LEFT OUTER JOIN "skills" ON "skills"."profile_id" = "profiles"."id" WHERE "skills"."name" = 'baz' AND "profiles"."id" = 2  => #<ActiveRecord::Relation [#<Profile id: 2, created_at: "2017-07-28 21:53:34", updated_at: "2017-07-28 21:53:34">]> 

Update 2

Downvoting an answer because you changed your question later is poor form.

You should change your model relationships from has_many and belongs_to to has_and_belongs_to_many. This will allow you to stop recording a new skill every time; if someone adds the skill administration and then later on someone else adds that skill, you don't have to create a new skill. You just re-use the existing skill and associate it with multiple profiles:

class Profile < ApplicationRecord   has_and_belongs_to_many :skills end  class Skill < ApplicationRecord   has_and_belongs_to_many :profiles end 

Add a join table with a unique index (so each profile can have each skill once and only once):

class Join < ActiveRecord::Migration[5.1]   def change     create_table :profiles_skills, id: false do |t|       t.belongs_to :profile, index: true       t.belongs_to :skill, index: true       t.index ["profile_id", "skill_id"], name: "index_profiles_skills_on_profile_id_skill_id", unique: true, using: :btree     end   end end 

Create your models:

Profile.create Profile.create Skill.create(name: 'foo') Skill.create(name: 'bar') Skill.create(name: 'baz') Profile.first.skills << Skill.first Profile.first.skills << Skill.second Profile.second.skills << Skill.second Profile.second.skills << Skill.third 

And then run your query to return just the first profile:

skills = %w(foo bar).uniq Profile.includes(:skills).where('skills.name' => skills).group(:id).having("count(skills.id) >= #{skills.size}")   SQL (0.4ms)  SELECT  DISTINCT "profiles"."id" FROM "profiles" LEFT OUTER JOIN "profiles_skills" ON "profiles_skills"."profile_id" = "profiles"."id" LEFT OUTER JOIN "skills" ON "skills"."id" = "profiles_skills"."skill_id" WHERE "skills"."name" IN ('foo', 'bar') GROUP BY "profiles"."id" HAVING (count(skills.id) = 2) LIMIT ?  [["LIMIT", 11]]   SQL (0.2ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."created_at" AS t0_r1, "profiles"."updated_at" AS t0_r2, "skills"."id" AS t1_r0, "skills"."name" AS t1_r1, "skills"."profile_id" AS t1_r2, "skills"."created_at" AS t1_r3, "skills"."updated_at" AS t1_r4 FROM "profiles" LEFT OUTER JOIN "profiles_skills" ON "profiles_skills"."profile_id" = "profiles"."id" LEFT OUTER JOIN "skills" ON "skills"."id" = "profiles_skills"."skill_id" WHERE "skills"."name" IN ('foo', 'bar') AND "profiles"."id" = 1 GROUP BY "profiles"."id" HAVING (count(skills.id) = 2)  => #<ActiveRecord::Relation [#<Profile id: 1, created_at: "2017-07-28 21:52:56", updated_at: "2017-07-28 21:52:56">]> 

Confirm with additional testing:

Should return both profiles:

skills = %w(bar).uniq Profile.includes(:skills).where('skills.name' => skills).group(:id).having("count(skills.id) >= #{skills.size}")   SQL (0.4ms)  SELECT  DISTINCT "profiles"."id" FROM "profiles" LEFT OUTER JOIN "profiles_skills" ON "profiles_skills"."profile_id" = "profiles"."id" LEFT OUTER JOIN "skills" ON "skills"."id" = "profiles_skills"."skill_id" WHERE "skills"."name" = 'bar' GROUP BY "profiles"."id" HAVING (count(skills.id) >= 1) LIMIT ?  [["LIMIT", 11]]   SQL (0.3ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."created_at" AS t0_r1, "profiles"."updated_at" AS t0_r2, "skills"."id" AS t1_r0, "skills"."name" AS t1_r1, "skills"."profile_id" AS t1_r2, "skills"."created_at" AS t1_r3, "skills"."updated_at" AS t1_r4 FROM "profiles" LEFT OUTER JOIN "profiles_skills" ON "profiles_skills"."profile_id" = "profiles"."id" LEFT OUTER JOIN "skills" ON "skills"."id" = "profiles_skills"."skill_id" WHERE "skills"."name" = 'bar' AND "profiles"."id" IN (1, 2) GROUP BY "profiles"."id" HAVING (count(skills.id) >= 1)  => #<ActiveRecord::Relation [#<Profile id: 1, created_at: "2017-07-28 21:52:56", updated_at: "2017-07-28 21:52:56">, #<Profile id: 2, created_at: "2017-07-28 21:53:34", updated_at: "2017-07-28 21:53:34">]> 

Should return just the second profile:

skills = %w(bar baz).uniq   SQL (0.3ms)  SELECT  DISTINCT "profiles"."id" FROM "profiles" LEFT OUTER JOIN "profiles_skills" ON "profiles_skills"."profile_id" = "profiles"."id" LEFT OUTER JOIN "skills" ON "skills"."id" = "profiles_skills"."skill_id" WHERE "skills"."name" IN ('bar', 'baz') GROUP BY "profiles"."id" HAVING (count(skills.id) >= 2) LIMIT ?  [["LIMIT", 11]]   SQL (0.2ms)  SELECT "profiles"."id" AS t0_r0, "profiles"."created_at" AS t0_r1, "profiles"."updated_at" AS t0_r2, "skills"."id" AS t1_r0, "skills"."name" AS t1_r1, "skills"."profile_id" AS t1_r2, "skills"."created_at" AS t1_r3, "skills"."updated_at" AS t1_r4 FROM "profiles" LEFT OUTER JOIN "profiles_skills" ON "profiles_skills"."profile_id" = "profiles"."id" LEFT OUTER JOIN "skills" ON "skills"."id" = "profiles_skills"."skill_id" WHERE "skills"."name" IN ('bar', 'baz') AND "profiles"."id" = 2 GROUP BY "profiles"."id" HAVING (count(skills.id) >= 2)  => #<ActiveRecord::Relation [#<Profile id: 2, created_at: "2017-07-28 21:53:34", updated_at: "2017-07-28 21:53:34">]> 

Should return no profiles:

skills = %w(foo baz).uniq Profile.includes(:skills).where('skills.name' => skills).group(:id).having("count(skills.id) >= #{skills.size}")   SQL (0.3ms)  SELECT  DISTINCT "profiles"."id" FROM "profiles" LEFT OUTER JOIN "profiles_skills" ON "profiles_skills"."profile_id" = "profiles"."id" LEFT OUTER JOIN "skills" ON "skills"."id" = "profiles_skills"."skill_id" WHERE "skills"."name" IN ('foo', 'baz') GROUP BY "profiles"."id" HAVING (count(skills.id) >= 2) LIMIT ?  [["LIMIT", 11]]  => #<ActiveRecord::Relation []> 

Answers 3

PostgreSQL dependent solution:

where_clause = <<~SQL   ARRAY(     SELECT name FROM skills WHERE profile_id = profiles.id   ) @> ARRAY[?] SQL Profile.where(where_clause, %w[skill1 skill2]) 

It works, but it makes sense to change DB structure for speed-up. There are two options:

  • has_and_belongs_to_many way adds consistency (skills tables turns into the dictionary) and ability to use indexes
  • skills as array|jsonb column of profile - adds fast search by index without sub-selects or joins.

Answers 4

I would use EXISTS with a correlated sub-query, like this:

required_skills = %w{accounting administration} q = Profile.where("1=1") required_skills.each do |sk|   q = q.where(<<-EOQ, sk)     EXISTS (SELECT 1             FROM   skills s             WHERE  s.profile_id = profiles.id             AND    s.name = ?)   EOQ end 

There are some other ideas at this similar question but I think in your case multiple EXISTS clauses is the simplest and most likely fastest.

(By the way in Rails 4+ you can start with Profile.all instead of Profile.where("1=1"), because all returns a Relation, but in the old days it used to return an array.)

Answers 5

The problem with the following query

Profile.includes(:skills).where(skills: { name: ["accounting" , "administration"] } ) is that it create a query with IN operator like IN ('Accounting', 'Administration')

Now as per the SQA standard, it will match all the records which matches any value and not all the values from the array.

Here is a simplest solution

skills = ["accounting" , "administration"]  Profile.includes(:skills).where(skills: { name: skills }).group(:profile_id).having("count(*) = #{skills.length}") 

P.S. This assumes you will have at least one skill. Adjust having condition as per your usecase

Read More

Friday, May 5, 2017

RAILS: How to eliminate `translation missing` from some I18n.t in production (I18n.t fallback enabled)?

Leave a Comment

In my Rails 4.2 app, all modules are developed with I18n.t(). Here is an example of the index.html.erb:

<table class="table table-hover">   <thead>         <tr>       <th><%= t('Create Date') %></th>       <th><%= t(@for_which.sub('_', ' ').titleize) %></th>       <th><%= t('Brief Note') %></th>       <th><%= t('Ranking Index') %></th>       <th><%= t('Active') %></th>       <th><%= t('Entered By') %></th>       <th></th>       <th></th>     </tr>      </thead>        <tbody> 

In local.rb under initializers, local is set to en:

I18n.enforce_available_locales = false I18n.default_locale = 'en' if Rails.env.production? || Rails.env.development? I18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')] 

But I still see error of translation missing from some of the I18n.t in both production and development, such as tab and index title as below: enter image description here

How do I get rid of error of translation missing?

UPDATE: The error translation missing shows up in production even with the following I18n.t fallback in environment/production.rb:

 # Enable locale fallbacks for I18n (makes lookups for any locale fall back to   # the I18n.default_locale when a translation cannot be found).   config.i18n.fallbacks = true 

UPDATE: Added CSS:

//hide all "translation missing" warnings: body.production span.translation_missing {   display: none; } 

But words on tab, buttons, and table header disappear: enter image description here

Here is portion of html source showing for one of the tab Employee Infos:

            <li class="dropdown">         <a id="dropdownuser" href="#" data-toggle="dropdown" class="dropdown-toggle" data-toggle="tooltip" data-placement="bottom" ><span class="glyphicons glyphicons-yen text-danger"></span> <span class="translation_missing" title="translation missing: en.Employee Info">Employee Info</span> <b class="caret" id="caret_medium"></b></a>               <ul id="banktransaction" class="dropdown-menu" role="menu">                  <li><a href="/tt/view_handler?index=1&amp;url=/tt/tsheet/employee_infos"><i class='glyphicon glyphicon-list'></i> translation missing: en.List</a></li>                 <li></li>                 <li><a href="/tt/view_handler?index=1&amp;url=/tt/tsheet/employee_infos/search"><i class='glyphicon glyphicon-list-alt'></i> translation missing: en.Search</a></li>                               </ul>             </li> 

2 Answers

Answers 1

in your #config/application.rb file you can do something like this

Rails.application.configure do |config|   config.action_view.raise_on_missing_translations = false end 

you can get more here

I hope that this is able to help you :)

Answers 2

Judging from the Rails 4.2 translate helper source code, I'm afraid you cannot simply switch off the warning message by a general setting.

From the ActionView code it is apparent that the translate helper by default forces raising an exception when passing the translation to the underlying I18n library. This behavior can be circumvented by a raise: false option passed to the translate helper and overriding the exception handler in the I18n library to return an empty string on missing translations. See the following tests in the Rails console:

# by default, the ActionView translate helper returns the "translation missing" # span on missing translation: helper.t('aa') => "<span class=\"translation_missing\" title=\"translation missing: en.aa\">Aa</span>"  # now let's force I18n library NOT to raise exception on missing translation: helper.t('aa',  raise: false) => "translation missing: en.aa"     # no SPAN any more, but still a warning message  # now let's tell I18n library to return nothing on missing translations I18n.exception_handler = ->(*args) { "" } helper.t('aa',  raise: false) => ""                               # finally this returns an empty string 

Although this approach works, it forces you to add raise: false parameter to all calls of t() in the templates which is probably not what you want.

However, there is a simpler solution:

Solution: hide the spans in your CSS

Yoy can leverage the fact that ActionView by default returns a SPAN with the translation_missing class as the warning about missing translation. Thus, you can simply hide all these spans in your CSS to get rid of the warnings:

# hide all "translation missing" warnings: span.translation_missing {   display: none; } 
Read More

Thursday, April 20, 2017

Update Rails view with Faye from Database change (after_commit callback) on model

Leave a Comment

I am very puzzled and this is my first Faye or Pub/Sub implementation so please forgive me if this is a basic questions. I have not found answers anywhere else. Any help is appreciated.

How can I call and update a Rails view page from a model callback (after_commit, after_save etc)? I need a javascript code that does the view update to run from views/conferences/_show_current_participants.js.erb once the after_commit callback fires.

I have it setup and It Works to have the javascript execute and view update if I use a link_to tag with return => true on the view. The thing is I will Not have Any user interaction and need to push view updates to the page base solely on database changes (hence after_commit callback on model). Is this not the right tool/design pattern/approach?

I tried making an HTTP get request on the after_commit callback to http://localhost:3000/conferences/conference_id/_show_current_participants_url but that did not trigger Faye/the javascript to be executed on the page view.

Here it is: _show_current_participants.js.erb

<% participant_broadcast "/conferences/#{@conference.id}" do %>   alert('_show_current_participants.js.erb loaded');   $("#current_participants_js").html("<%= escape_javascript(render partial: 'conferences/show_current_participants.html', locals: { conference: @conference } ) %>"); <%end%> 

This works like a charm if I set it to trigger on a link_to tag with remote => true:

<li><%= link_to "Faye CALL", "#{@conference.id}/_show_current_participants", remote: true %></li> 

How can I modify this setup so instead of having to click on a link the Faye and subsequent partial's javascript gets activated on the after_commit model callback? Is this the wrong approach? How else can I tell my view to update based on a database change? Any help is appreciated. Thank you so very much to any kind soul willing to help me find the right direction.

Versions:

Faye 1.2.4 (not faye-rails)
Rails 4.1.5
Ruby 2.3.0
At this point more than a super pretty solution I am looking for something that works.

1 Answers

Answers 1

You should subscribe to messages with a javascript callback:

<script>    $(function() {        // Create a new client to connect to Faye        var client = new Faye.Client('http://localhost:3000/conferences');         // Subscribe to the public channel        var public_subscription = client.subscribe('/#{@conference.id}/_show_current_participants', function(data) {           $("#current_participants_js").html(data);         });    }); </script> 
Read More

Thursday, January 19, 2017

Routes not working correctly

Leave a Comment

EDIT: Thanks for the replies, I tried everything listed below but still now luck. If I type localhosts/posts/new it takes me to the form, however the link does not work when I click from the navigation bar. I've updated the code and included my rake routes results.

I am new to ruby and working through a tutorial, however one of my links is not working and not sure what is happening.

My navigation link to create a new post is not taking me to the correct page, when I click the link to the "posts_path" the page does not change.

I can create a new posts by typing in the /posts/new in the address bar, but when I click the "New Post" link on the nav bar the page does not update (although the url displays /posts). Any idea how to fix this?

config/routes.rb

Rails.application.routes.draw do get 'sessions/new' root 'static_pages#home' get  '/search', to: 'static_pages#search' get  '/login', to: 'sessions#new' get  '/posts', to: 'posts#new', as: 'new_post' post  '/login', to: 'sessions#create' delete  '/logout', to: 'sessions#destroy' get  '/signup', to: 'users#new' get 'users/new' get 'static_pages/home' get 'posts/new' get 'sessions/new' resources :users resources :account_activations, only: [:edit] resources :password_resets, only: [:new, :create, :edit, :update] resources :posts, only: [:new, :create, :destroy] end 

app/views/layouts/_header.html.erb

<header class="navbar navbar-fixed-top navbar-inverse"> <div class="container">   <% link_to "sample app", root_path, id: "logo" %>     <nav>       <ul class="nav navbar-nav navbar-right">         <li><%= link_to "Home", root_path %></li>         <li><%= link_to "Search", search_path %></li>           <% if logged_in? %>             <li><%= link_to "Users", users_path %></li>             <li><%= link_to "Posts", posts_new_path %></li>             <li class="dropdown">              <a href='#' class="dropdown-toggle" data-toggle="dropdown">Account <b class="caret"></b></a>              <ul class="dropdown-menu">               <li><%= link_to "Profile", current_user %></li>               <li><%= link_to "Settings", edit_user_path(current_user) %></li>               <li class="divider"></li>               <li><%= link_to "Logout", logout_path, method: "delete" %></li>              </ul>            </li>            <% else %>              <li><%= link_to "Log in", login_path %></li>            <% end %>           </ul>        </nav>   </div> 

posts_controller.rb

class PostsController < ApplicationController     before_action :logged_in_user, only: [:create, :destroy]     before_action :correct_user, only: :destroy      def create             @post = current_user.posts.build(post_params)             if @post.save                     flash[:success] = "Post created!"                     redirect_to root_url             else                     @feed_items = []                     render 'static_pages/home'             end     end      def destroy             @post.destroy             flash[:success] = "Post Deleted"             redirect_to request.referrer || root_url     end     def new        @post = current_user.posts.build if logged_in?     end      private      def post_params             params.require(:post).permit(:description, :picture)     end      def correct_user             @post = current_user.posts.find_by(id:params[:id])             redirect_to root_url if @post.nil?     end end 

rake routes:

password_resets_new     GET     /password_resets/new(.:format)          password_resets#new password_resets_edit    GET     /password_resets/edit(.:format)         password_resets#edit sessions_new            GET     /sessions/new(.:format)                 sessions#new root                    GET     /                                       static_pages#home search                  GET     /search(.:format)                       static_pages#search login                   GET     /login(.:format)                        sessions#new new_post                GET     /posts(.:format)                        posts#new                         POST    /login(.:format)                        sessions#create logout                  DELETE  /logout(.:format)                       sessions#destroy signup                  GET     /signup(.:format)                       users#new users_new               GET     /users/new(.:format)                    users#new static_pages_home       GET     /static_pages/home(.:format)            static_pages#home static_pages_about      GET     /static_pages/about(.:format)           static_pages#about static_pages_search     GET     /static_pages/search(.:format)          static_pages#search posts_new               GET     /posts/new(.:format)                    posts#new                         GET     /password_resets/new(.:format)          password_resets#new                         GET     /password_resets/edit(.:format)         password_resets#edit                         GET     /sessions/new(.:format)                 sessions#new help                    GET     /help(.:format)                         static_pages#help about                   GET     /about(.:format)                        static_pages#about contact                 GET     /contact(.:format)                      static_pages#contact users                   GET     /users(.:format)                        users#index                         POST    /users(.:format)                        users#create new_user                GET     /users/new(.:format)                    users#new edit_user               GET     /users/:id/edit(.:format)               users#edit user                    GET     /users/:id(.:format)                    users#show                         PATCH   /users/:id(.:format)                    users#update                         PUT     /users/:id(.:format)                    users#update                         DELETE  /users/:id(.:format)                    users#destroy edit_account_activation GET     /account_activations/:id/edit(.:format) account_activations#edit password_resets         POST    /password_resets(.:format)              password_resets#create new_password_reset      GET     /password_resets/new(.:format)          password_resets#new edit_password_reset     GET     /password_resets/:id/edit(.:format)     password_resets#edit password_reset          PATCH   /password_resets/:id(.:format)          password_resets#update                         PUT     /password_resets/:id(.:format)          password_resets#update posts                   POST    /posts(.:format)                        posts#create                         GET     /posts/new(.:format)                    posts#new post                    DELETE  /posts/:id(.:format)                    posts#destroy 

11 Answers

Answers 1

I would suggest that you remove get 'posts/new' & get '/posts', to: 'posts#new', as: 'new_post' as these are duplicate routes.

You already have the correct route created in the route resources :posts, only: [:new, :create, :destroy]. By including new, Rails is doing this portion for you. See here: http://guides.rubyonrails.org/v4.2/routing.html#crud-verbs-and-actions

Then you should be able to use the link that everyone else has posted. <%= link_to "New Post", new_post_path %> based on the guide here: http://guides.rubyonrails.org/v4.2/routing.html#path-and-url-helpers

Answers 2

The problem is there is conflict occurring in your routes. You have defined routes twice for new

get /posts', to: 'posts#new', as: 'new_post' 

and

resources :posts, only: [:new, :create, :destroy] 

now there are 2 paths for posts#new. I suggest u remove first one. Change your html to

<li><%= link_to 'New Post', posts_path %></li> 

and it should work fine.

Answers 3

i went through your code...and this is what i recommend to add/edit changes..and sure it should work :).

  1. for routes.rb,its looks good BUT there is a duplicate url entry.So either remove get 'posts/new' or resources :posts, only: [:new, :create, :destroy] as they both will create a duplicate entry for posts#new.You can verify this by outputting your routes in seperate txt file by rake routes >> path.txt
  2. in app/views/layouts/_header.html.erb,its good too and dont need any change.
  3. in posts_controller.rb,there is a condition added for only logged in user,Kindly check if you are logged in else remove that condition and check again.
  4. Finally,debug using F12 in chrome/firefox and see what log do you get in web browser console before and after click to check is there some javascript error or not.

Answers 4

Remove get 'sessions/new' & get '/posts', to: 'posts#new', as: 'new_post'

Restart server

and try link_to "Posts", posts_new_path, method: :post

Should work

Answers 5

code for link to new post

<%= link_to "New Post", new_post_path %> 

Answers 6

Try new_post_path

Also, rake routes in terminal will list all the routes and associated helpers for you to double check against.

Finally, adding 'as' to: get '/posts', to: 'posts#new', as: 'new_post' in your routes file will allow you to define your own path name (in this case new_post_path, but you can set it as anything you'd like).

Answers 7

<%= link_to "Posts", posts_path %> corresponds to index action not to the new action. 

Remove the only condition for your posts controller in routes.rb which will create all the basic routes needed rather than specific routes.

resources :posts 

So, new_post_path returns /posts/new

Finally add a link link <%= link_to 'New Post', new_post_path %>

Answers 8

This may be helps to redirect,
in routes.rb,

resources :posts   

It gives the paths to all default controller methods like index, new, create, edit, update, show, destroy. Then check with rake routes. Get the corresponding path like,

new_post GET      /posts/new(.:format)                    posts#new   

if it correct means give the url like,

<%= link_to 'New Post', new_post_path %>
It redirects to method new in controller and render corresponding html.erb page. This url formed by the routes.rb.

OR

push the redirection url manually.In html page,

<%= button_tag "New", :onclick => "getNew()" %>    function getNew(){         var form = document.forms[0];         // get the id and value with any variable //          form.method = "post";                // pass the value to parameters //         form.var name = column name; (description r picture)          form.action = "posts/new";         form.submit();     }   

in routes.rb,

match '/posts/new' => 'posts#new', via: [:get, :post]   

It makes the manual redirection url. It calls the new in controller method.
Let me know your feedback! Thanks

Answers 9

Rails scans the routes from top to bottom i.e. routes.rb. Whenever it finds the matching routes corresponding controller#action gets executed and remaining all will be skipped(later routes after match found).

In this case routes are conflicting, So do bellow changeseverything will work fine. config/routes.rb

Rails.application.routes.draw do get 'sessions/new' root 'static_pages#home' get  '/search', to: 'static_pages#search' get  '/login', to: 'sessions#new' #get  '/posts', to: 'posts#new', as: 'new_post' #not required as resources :posts will do the job in last line post  '/login', to: 'sessions#create' delete  '/logout', to: 'sessions#destroy' get  '/signup', to: 'users#new' get 'users/new' get 'static_pages/home' get 'posts/new', to: 'posts#new', as: 'posts_new_path'  #Made changes here according to helper used in view 'posts_new_path' get 'sessions/new' resources :users resources :account_activations, only: [:edit] resources :password_resets, only: [:new, :create, :edit, :update] resources :posts, only: [:new, :create, :destroy] end  

Answers 10

As per your rake routes output the following should work

<%= link_to "New Post", posts_new_path %> 

Please let us know whether there any error comming in the console log on clicking the new post link.

Answers 11

The bottom line is that you're trying to do things in a non-Rails manner. Rails favors convention over configuration, meaning if you don't do things the Rails way, you're going to have a bad time.

This means you should clean up your routes until you have no unnecessary duplication. Right now you have 3 different routes that go to posts#new each with a different path prefix.

I'd remove:

  • get '/posts', to: 'posts#new', as: 'new_post'
  • get 'posts/new'

since resources :posts, only: [:new, :create, :destroy] already creates that route. Then your new_post_path helper should create the correct URL and your routes will have no ambiguity.

Read More

Sunday, September 25, 2016

Authenticated Route not working for Rspec test

Leave a Comment

I'm following this post about setting up authentication in the routes of my Rails 4 application.

Here is my routes.rb file:

Rails.application.routes.draw do    devise_for :employees, :controllers => { registrations: 'employees/registrations' }   devise_for :clients     authenticate :employee do     resources :quotation_requests, only: [:show, :edit,:index, :update, :destroy]   end    resources :quotation_requests, only: [:new, :create]    get '/dashboard' => 'dashboard#show', as: 'show_dashboard'    root to: 'home#index' end 

Here is my quotation_requests_controller_spec.rb file:

require 'rails_helper'  RSpec.describe QuotationRequestsController, type: :controller do       describe "GET index" do         it "renders :index template" do             get :index             expect(response).to render_template(:index)         end          it "assigns quotation requests to template" do             quotation_requests = FactoryGirl.create_list(:quotation_request, 3)             get :index             expect(assigns(:quotation_requests)).to match_array(quotation_requests)         end      end      describe "GET edit" do         let(:quotation_request) { FactoryGirl.create(:quotation_request)}          it "renders :edit template" do             get :edit, id: quotation_request             expect(response).to render_template(:edit)         end         it "assigns the requested quotation request to template" do             get :edit, id: quotation_request             expect(assigns(:quotation_request)).to eq(quotation_request)         end     end      describe "PUT update" do         let(:quotation_request) { FactoryGirl.create(:quotation_request)}          context "valid data" do             new_text = Faker::Lorem.sentence(word_count=500)             let(:valid_data) { FactoryGirl.attributes_for(:quotation_request, sample_text: new_text)}              it "redirects to quotation_request#showtemplate" do                 put :update, id: quotation_request, quotation_request: valid_data                 expect(response).to redirect_to(quotation_request)             end             it "updates quotation request in the database" do                 put :update, id: quotation_request, quotation_request: valid_data                 quotation_request.reload #need to reload the object because we have just updated it in the database so need to get the new values                 expect(quotation_request.sample_text).to eq(new_text)             end         end          context "invalid data" do             let(:invalid_data) { FactoryGirl.attributes_for(:quotation_request, sample_text: "", number_of_words: 400)}              it "renders the :edit template" do                 put :update, id: quotation_request, quotation_request: invalid_data                 expect(response).to render_template(:edit)             end             it "does not update the quotation_request in the database" do                 put :update, id: quotation_request, quotation_request: invalid_data                 quotation_request.reload                 expect(quotation_request.number_of_words).not_to eq(400)             end         end     end      describe "GET new", new: true do         it "renders :new template" do             get :new             expect(response).to render_template(:new)         end         it "assigns new QuotationRequest to @quotation_request" do             get :new             expect(assigns(:quotation_request)).to be_a_new(QuotationRequest)         end     end      describe "GET show" do          #this test requires that there be a quotation request in the database         let(:quotation_request) { FactoryGirl.create(:quotation_request) }          context 'invalid request' do              it "does not render :show template if an employee or client is not signed in" do                  #setup                 quotation_request =  create(:quotation_request)                  #exercise                 get :show, id: quotation_request                  #verification                 expect(response).to_not render_template(:show)              end          end          context 'valid request' do              sign_in_proofreader              it "renders :show template if an employee or client is signed in" do                  #setup                 quotation_request =  create(:quotation_request)                   #exercise                 get :show, id: quotation_request                  #verification                 expect(response).to render_template(:show)             end              it "assigns requested quotation_request to @quotation_request" do                 get :show, id:  quotation_request                 expect(assigns(:quotation_request)).to eq(quotation_request)             end          end     end      describe "POST create", post: true do         context "valid data" do              let(:valid_data) {FactoryGirl.nested_attributes_for(:quotation_request)}              it "redirects to quotation_requests#show" do                 post :create, quotation_request: valid_data                 expect(response).to redirect_to(quotation_request_path(assigns[:quotation_request]))             end              it "creates new quotation_request in database" do             expect {                 post :create, quotation_request: valid_data                 }.to change(QuotationRequest, :count).by(1)             end         end          context "invalid data" do         let(:invalid_data) {FactoryGirl.nested_attributes_for(:quotation_request).merge(sample_text: 'not enough sample text')}              it "renders :new template" do                 post :create, quotation_request: invalid_data                 expect(response).to render_template(:new)             end              it "doesn't creates new quotation_request in database" do                 expect {                     post :create, quotation_request: invalid_data                 }.not_to change(QuotationRequest, :count)             end         end     end      describe "DELETE destroy" do          let(:quotation_request) { FactoryGirl.create(:quotation_request) }          it "redirects to the quotation request#index" do             delete :destroy, id: quotation_request             expect(response).to redirect_to(quotation_requests_path)         end         it "delets the quotation request from the database" do             delete :destroy, id: quotation_request             expect(QuotationRequest.exists?(quotation_request.id)).to be_falsy         end      end end 

My quotation_requests_controller.rb

class QuotationRequestsController < ApplicationController # before_action :authenticate_employee!, :only => [:show]      def index         @quotation_requests =  QuotationRequest.all     end      def new         @quotation_request = QuotationRequest.new         @quotation_request.build_client     end      def edit         @quotation_request = QuotationRequest.find(params[:id])     end      def create       client = Client.find_or_create(quotation_request_params[:client_attributes])       @quotation_request = QuotationRequest.new(quotation_request_params.except(:client_attributes).merge(client: client))       if @quotation_request.save         ClientMailer.quotation_request_created(client.email, @quotation_request.id).deliver_now         redirect_to @quotation_request, notice: 'Thank you.'       else         render :new       end     end      def show         @quotation_request = QuotationRequest.find(params[:id])     end      def update         @quotation_request = QuotationRequest.find(params[:id])         if @quotation_request.update(quotation_request_params)             redirect_to @quotation_request         else             render :edit         end     end      def destroy         QuotationRequest.destroy(params[:id])         redirect_to quotation_requests_path     end      private      def quotation_request_params         params.require(:quotation_request).permit(:number_of_words, :return_date, :sample_text, :client_attributes => [:first_name, :last_name, :email])     end  end 

I know the routes authentication works because if I test them in the browser I get redirected to the sign_in page. However, the tests don't pass in Rspec.

if I put this code in the quotation_requests_controller.rb:

 before_action :authenticate_employee!, :only => [:show] 

The rspec tests pass. So for some reason Rspec does not register the authentication of the routes.

Here is the output from Rspec for the tests run with the authenticated routes:

QuotationRequestsController   GET index     valid request       renders :index template for signed in employee       assigns quotation requests to template     invalid request       does not render :index template without a signed in employee (FAILED - 1)   GET edit     valid request       renders :edit template with a signed in employee       assigns the requested quotation request to template     invalid request       does not render the :edit template without a signed in employee (FAILED - 2)   PUT update     valid request       valid data         redirects to quotation_request#showtemplate         updates quotation request in the database       invalid data         renders the :edit template         does not update the quotation_request in the database     invalid request       redirects user to the sign in page (FAILED - 3)   GET new     renders :new template     assigns new QuotationRequest to @quotation_request   GET show     invalid request       does not render :show template if an employee or client is not signed in (FAILED - 4)     valid request       renders :show template if an employee or client is signed in       assigns requested quotation_request to @quotation_request   POST create     valid data       redirects to quotation_requests#show       creates new quotation_request in database     invalid data       renders :new template       doesn't creates new quotation_request in database   DELETE destroy     valid request       redirects to the quotation request#index       delets the quotation request from the database     invalid request       does not delete the quotation request without a signed in employee (FAILED - 5)  Failures:    1) QuotationRequestsController GET index invalid request does not render :index template without a signed in employee      Failure/Error: expect(response).to_not render_template(:index)        Didn't expect to render index      # ./spec/controllers/quotation_requests_controller_spec.rb:43:in `block (4 levels) in <top (required)>'      # -e:1:in `<main>'    2) QuotationRequestsController GET edit invalid request does not render the :edit template without a signed in employee      Failure/Error: expect(response).to_not render_template(:edit)        Didn't expect to render edit      # ./spec/controllers/quotation_requests_controller_spec.rb:92:in `block (4 levels) in <top (required)>'      # -e:1:in `<main>'    3) QuotationRequestsController PUT update invalid request redirects user to the sign in page      Failure/Error: expect(response).to_not redirect_to(quotation_request)        Didn't expect to redirect to #<QuotationRequest:0x007fe7eb69c8c0>      # ./spec/controllers/quotation_requests_controller_spec.rb:182:in `block (4 levels) in <top (required)>'      # -e:1:in `<main>'    4) QuotationRequestsController GET show invalid request does not render :show template if an employee or client is not signed in      Failure/Error: expect(response).to_not render_template(:show)        Didn't expect to render show      # ./spec/controllers/quotation_requests_controller_spec.rb:217:in `block (4 levels) in <top (required)>'      # -e:1:in `<main>'    5) QuotationRequestsController DELETE destroy invalid request does not delete the quotation request without a signed in employee      Failure/Error: expect(QuotationRequest.exists?(quotation_request.id)).to be_truthy         expected: truthy value             got: false      # ./spec/controllers/quotation_requests_controller_spec.rb:361:in `block (4 levels) in <top (required)>'      # -e:1:in `<main>'  Finished in 2.11 seconds (files took 1.75 seconds to load) 23 examples, 5 failures  Failed examples:  rspec ./spec/controllers/quotation_requests_controller_spec.rb:37 # QuotationRequestsController GET index invalid request does not render :index template without a signed in employee rspec ./spec/controllers/quotation_requests_controller_spec.rb:83 # QuotationRequestsController GET edit invalid request does not render the :edit template without a signed in employee rspec ./spec/controllers/quotation_requests_controller_spec.rb:171 # QuotationRequestsController PUT update invalid request redirects user to the sign in page rspec ./spec/controllers/quotation_requests_controller_spec.rb:208 # QuotationRequestsController GET show invalid request does not render :show template if an employee or client is not signed in rspec ./spec/cont 

Why do the routes I have written not work in Rspec tests?

1 Answers

Answers 1

I take it you are using rspec-rails in your rails app. Rspec-rails sets up a lot of convenience methods for you, but it also introduces some black-magic, which can lead to some unexpected results - like this.

As you can see here it is explained in the comments for controller specs:

# Supports a simple DSL for specifying behavior of ApplicationController. # Creates an anonymous subclass of ApplicationController and evals the # `body` in that context. Also sets up implicit routes for this # controller, that are separate from those defined in "config/routes.rb". 

I guess the logic here is, controller features are different from routing and should be tested separately (and indeed rspec-rails offers a test group for routing), so we do not need the routes for controller specs, meaning you should be able to test your controller without setting up the routes.

In my oppinion, testing the redirect for unauthenticated users is more of an integration test, since it requires multiple parts of your application to work together and as such should not be tested in the controller context, but rather as a feature in some blackbox test.

You can write integration tests by placing them in one of these directories spec/requests, spec/api, and spec/integration or by explicitely declaring their type with

RSpec.describe "Something", type: :request do 

or place it in spec/features or declare the type as

RSpec.describe "Something", type: :feature do 

depending on which level you want to test the redirect (meaning: only test the request-response cycle, or run it in a simulated browser). Please refer to the documentation for integration tests on the rspec-rails github page for more information.

Read More

Friday, July 22, 2016

How do I force a certain URL after a Rails redirect?

Leave a Comment

I’m using Rails 4.2.3. I have the following in the create method of my controller

    format.html { redirect_to controller: "my_objects", action: "index", notice: 'Saved successfully.' } 

However when I redirect, the URL is actually

http://mydomein.devbox.com:3000/my_objects 

and I want it to be

http://mydomein.devbox.com:3000/my_objects/index 

How can I force the URL to be “/index” instead of what its appearing as now?

Edit: Here are the logs when visiting /my_objects/index:

Started GET "/my_objects/index" for 127.0.0.1 at 2016-07-12 12:17:25 -0500 Processing by MyObjectsController#index as HTML DEPRECATION WARNING: Passing a nested array to Active Record finder methods is deprecated and will be removed. Flatten your array before using it for 'IN' conditions. (called  from country_code_select at /Users/davea/Documents/workspace/runtrax/app/helpers/user_form_helper.rb:83)   Rendered my_objects/_add.html.erb (31.0ms)   Rendered my_objects/index.html.erb within layouts/race (46.0ms)   Rendered layouts/_navigation.html.erb (0.2ms)   Rendered layouts/_messages.html.erb (0.1ms)   Rendered my_objects/_tabs.html.erb (0.3ms) Completed 200 OK in 308ms (Views: 301.9ms | ActiveRecord: 4.8ms) 

Edit: Here is the relevant portion from the config/routes.rb file …

  get 'my_objects/index'   get 'my_objects/create'   resources :my_objects do     collection do       post 'create'       get 'import'       get 'index' => 'my_objects/index'       get 'search'       get 'stats'     end   end 

3 Answers

Answers 1

The redirected URL by rails convention is redirecting to the index action. Check your logs to see what happening. If you do /my_objects/index, you're telling rails you want the my_object with ID = index.

Answers 2

Can you please post your routes.rb because there you can specify how you get a route like this:

get 'my_objects/index' => 'my_objects#index'

and then in the controller you just do a

redirect_to my_objects

Answers 3

In the routes change this line

get "index" => "my_object#index" 

To

get "index" => "my_object#index", as: :my_object_index 

Then redirect to that path

redirect_to my_object_index_path, notice: "saved successfully" 
Read More

Tuesday, June 28, 2016

Rails 5 rendering from outside a controller with ApplicationController.renderer.render doesn't set variables on self

Leave a Comment

I'm using the Rails 5 ApplicationController.renderer.render method to render from within a model. I need to pass some variables to my layout which I have done using the locals option; this variable is then available in the layout if accessed directly, but not via self.

Here is how I have setup my render

html_string = ApplicationController.renderer.render(   file: "/#{template_path}/base/show",   :formats => [:pdf,:html],   locals: {     :@routing_form => self,     :controller_name => controller_name,     :action_name => action_name,     :current_user => current_user   },   :layout  => '/layouts/application' ) 

Then within the layout I want to do something like this.

<div id="foo" class="<%= self.action_name %>"> 

I was able to get this working by dropping self in this particular instance

<div id="foo" class="<%= action_name %>"> 

but now my concern is how would I set a variable so that it would work correctly with self? Previously I was using the render_anywhere gem and this was handled using rendering_controller.var = "value"

1 Answers

Answers 1

Since self is a keyword in Ruby, you cannot use it as a method call in your layout template, so you should use another name to pass with the locals.

You can pass something like my_object: self and it will work fine.

If you want to name the key with a @, you should put it inside a string '@my_object': self and calls it normally in your template: <%= @my_object.action_name%>

Read More

Thursday, June 23, 2016

How to get most clicked records and at-least one child levels resource will be include

Leave a Comment

I have models like this with polymorphic relationship

class Level1  has_and_belongs_to_many :level2s  has_many :resources ,:as => :mediable end  class Level2     has_and_belongs_to_many :level1s     has_many :level3s     has_many :resources ,:as => :mediable end  class Level3     belongs_to :level2     has_many :resources ,:as => :mediable end  class Resource     belongs_to :mediable , polymorphic: true     has_many :resources ,:as => :mediable     has_many :clicks ,:as => :mediable end  class click     belongs_to :clickable , polymorphic: true end 

When user add a resource in level1/level2/level3(image or media) I show these media somewhere where user can click on this and each click I save an entry in clicks table

Now I need to when user on level1's show page I need to show top 50 resources of the level1s and level2s combined based on the click counts and at least one resource will be fetched from database

I am going to try like this:

Resource.select("resources.*, count(clicks.id) as click_counts")             .joins( "INNER JOIN clicks ON clicks.clickable_id = resources.id AND clicks.clickable_type='Resource'" )             .where("(resources.mediable_id IN(1) AND resources.mediable_type='Level1') OR (resources.mediable_id IN(1, 2, 3, 4, 5) AND resources.mediable_type='Level2')")             .group("resources.id")             .order("click_counts").limit(50) 

It will return top 50 resources related to level 1 and its related level2s but not not guarantee to I have at least one resources related to level2.

can you help me how can I do that

There are possibilities a resource never clicked but I have to get that resources as well as I need at least one resource for each level So I think inner join should change to left outer

1 Answers

Answers 1

If is not a problem for you do a little extra computation, you can achieve it easily with:

resources = Resource.select("resources.*, count(clicks.id) as click_counts")             .joins( "INNER JOIN clicks ON clicks.clickable_id = resources.id AND clicks.clickable_type='Resource'" )             .where("(resources.mediable_id IN(1) AND resources.mediable_type='Level1') OR (resources.mediable_id IN(1, 2, 3, 4, 5) AND resources.mediable_type='Level2')")             .group("resources.id")             .order("click_counts").limit(50)  unless resources.pluck(:mediable_type).include? 'Level2'    resources = resources.limit(49) + Resource.select("resources.*, count(clicks.id) as click_counts")             .joins( "INNER JOIN clicks ON clicks.clickable_id = resources.id AND clicks.clickable_type='Resource'" )             .where("resources.mediable_id IN(1, 2, 3, 4, 5) AND resources.mediable_type='Level2'")             .group("resources.id")             .order("click_counts").limit(1) end 

Otherwise, you could try with something like this (not tested):

sub_select = "(    SELECT resources.*, count(clicks.id) as click_counts, 1 as SortKey    FROM resources     INNER JOIN clicks ON clicks.clickable_id = resources.id AND clicks.clickable_type='Resource'    WHERE resources.mediable_id IN(1, 2, 3, 4, 5) AND resources.mediable_type='Level2'    GROUP BY resources.id    ORDER BY mediable_type, click_counts     LIMIT 1     UNION ALL     SELECT resources.*, count(clicks.id) as click_counts, 2 as SortKey    FROM resources     INNER JOIN clicks ON clicks.clickable_id = resources.id AND clicks.clickable_type='Resource'    WHERE (resources.mediable_id IN(1) AND resources.mediable_type='Level1') OR (resources.mediable_id IN(1, 2, 3, 4, 5) AND resources.mediable_type='Level2')    GROUP BY resources.id    ORDER BY SortKey, mediable_type, click_counts) as t"  select_sql = "SELECT DISTINCT resources.*, click_counts FROM #{sub_select} LIMIT 50"  results = ActiveRecord::Base.connection.select_all(select_sql).rows # array results_ordered = results.sort { |a, b| a.last <=> b.last } 

Notes:

  • The SortKey extra attribute guarantee the queries order
  • UNION ALL does not eliminate any duplicate record. So we need to add a DISTINCT on resources.*, click_counts columns to remove a possibile duplicate record (the first of 'Level2')

Hope it helps!

Read More

Monday, May 2, 2016

Why does redirecting from HTTPS to HTTP fail in this Rails 4 app (OpenShift)?

Leave a Comment

When the user is on HTTP, I can successfully redirect him to a HTTPS (SSL) variant like so:

redirect_to { protocol: 'https://', domain: 'ssl.tld' }

However, when I want to do the reverse, it creates an infinite redirection loop. I've tried several variants. To mention some:

redirect_to { protocol: 'http://', domain: 'nonssl.tld' }

redirect_to "http://nonssl.tld#{request.fullpath}"

The loop, according to the log:

000.000.000.000 - - [21/Apr/2016:18:50:04 -0100] "GET /en HTTP/1.1" 302 887 "https://ssl.tld/en/users/sign_in" "= THE_USER_AGENT_HERE"

Whereas https://ssl.tld/en/users/sign_in apparantly is the referrer/the current page before redirection.

I wonder why the GET shows a path as opposed to a URL - especially given that redirect_to "http://nonssl.tld#{request.fullpath}" should explicitly be considered an absolute URL, according to the docs.


UPDATE Here is the relevant part from the application_controller's before_action:

exceptions = ['errors', 'subscriptions', 'users'] ssl_is_mandatory = ! exceptions.include?(controller_name) currently_on_ssl = request.ssl?  if currently_on_ssl   if !current_user && !ssl_is_mandatory     logger.debug "#{__method__}: Visitor currently on SSL, but SSL not desired. Redirecting to non_ssl"     redirect_to "http://my.domain#{request.fullpath}"   end  else   if current_user || ssl_is_mandatory     logger.debug "#{__method__}: Currently on no-SSL, but user in session or SSL mandatory. Redirecting to ssl"     redirect_to { protocol: 'https://', domain: 'my.ssldomain' }   end end 

0 Answers

Read More

Saturday, April 30, 2016

Rails - Keep a table out of structure.sql during migrations

Leave a Comment

It is straightforward to ignore tables when your schema format is :ruby, but is there a way to do it when your schema format is :sql?

Ideally something like this in environment.rb:

ActiveRecord::SQLDumper.ignore_tables = ['table_name'] 

After a quick perusal through the AR source code it looks unpromising.

1 Answers

Answers 1

There is currently no way to do this, when the schema format is set to :sql, Rails doesn't go through the regular SchemaDumper but instead uses the tasks in ActiveRecord::Tasks::PostgreSQLDatabaseTasks to do the dump, check it out here.

The code is quite straightforward. I came up with a simple patch for ActiveRecord that should work as expected. It relies on setting the tables to ignore in your database.yml file. It basically adds the following code:

ignore_tables = configuration['ignore_tables'] unless ignore_tables.blank?   args += ignore_tables.split(',').map do |table|     "-T #{table}"   end end 

I just submitted a pull request to rails with those changes. In case you'd want to test it.

Read More

Tuesday, April 26, 2016

How do I optimize an ActiveRecord find_in_batches query?

Leave a Comment

I'm using Rails 4.0.0 and Ruby 2.0.0. My Post (as in blog posts) model is associated with a user with a combination of the user's user_name, first_name, last_name. I'd like to migrate the data so that posts are associated to users by a foreign key, which is the user's id.

I have about 11 million records in the posts table.

I'm running the below code to migrate the data, using a rake task on a Linux server. However, my task keeps getting "Killed" by the sever, presumably due to the rake task, specifically the below code, consuming too much memory.

I've found that lowering the batch_size to 20 and increasing sleep(10) to sleep(60) allows the task to run longer, updating more records in total without being Killed, but takes significantly more time.

How can I optimize this code for speed and memory usage?

Post.where(user_id: nil).find_in_batches(batch_size: 1000) do |posts|   puts "*** Updating batch beginning with post #{posts.first.id}..."   sleep(10) # Hopefully, saving some memory usage.   posts.each do |post|     begin       user = User.find_by(user_name: post.user_name, first_name: post.first_name, last_name: post.last_name)       post.update(user_id: user.id)     rescue NoMethodError => error # user could be nil, so user.id will raise a NoMethodError       puts "No user found."     end   end   puts "*** Finished batch." end 

5 Answers

Answers 1

Do all the work in the database which is WAY faster than moving data back and forth.

This can be accomplished with ActiveRecord. Of course PLEASE test this before you unleash it on important data.

Post   .where(user_id: nil)   .joins("inner join users on posts.user_name = users.user_name")   .update_all("posts.user_id = users.id") 

Further, if posts have an index on user_id, and users has an index on user_name, then that will help this particular query run more quickly.

Answers 2

Check out the #uncached method on AR models. Basically, for request optimization, AR will cache a lot of query data as it is doing #find_in_batches, but it's a hinderance to large processing scripts like this.

Post.uncached do   # perform all your heavy query magic here end 

Ultimately, if that doesn't work, consider using the mysql2 gem to avoid the AR overhead, as long as you're not depending on any callbacks/business logic in the update.

Answers 3

If a join is possible I'd go with the approach from z5h. Otherwise you could add an index to the user model (possibly in a separate migration) and also skip the validations, callbacks and stuff when updating each post:

add_index :users, [:user_name, :first_name, :last_name] # Speed up search queries Post.where(user_id: nil).find_each do |post|   if user = User.find_by(user_name:  post.user_name,                          first_name: post.first_name,                          last_name:  post.last_name)     post.update_columns(user_id: user.id) # ...to skip validations and callbacks.   end end 

Please note that find_each is equivalent to find_in_batches + iterating over each post, but possibly not faster (see Rails Guides on Active Record Query Interface)

Good luck!

Answers 4

Combining other answers, I was able to join tables, and update multiple columns, in batches of 1000 rows, with a reduction in speed and without my process being killed by the server.

Here's the combines approach that I found to work best, keeping the code within the ActiveRecord API as much as possible.

Post.uncached do   Post.where(user_id: nil, organization_id: nil).find_each do |posts|     puts "** Updating batch beginning with post #{posts.first.id}..."      # Update 1000 records at once     posts.map!(&:id) # posts is an array, not a relation     Post.where(id: posts).       joins("INNER JOIN users ON (posts.user_name = users.user_name)").       joins("INNER JOIN organizations ON (organizations.id = users.organization_id)").       update_all("posts.user_id = users.id, posts.organization_id = organizations.id")      puts "** Finished batch."   end end 

Answers 5

Add new temporary boolean attribute updated

Post.where(updated: false).find_in_batches(batch_size: 1000) do |posts|   ActiveRecord::Base.transaction do     puts "*** Updating batch beginning with post #{posts.first.id}..."     posts.each do |post|       user = User.find_by(user_name: post.user_name, first_name: post.first_name, last_name: post.last_name)       if user         post.update_columns(user_id: user.id, updated: true)       else         post.update_columns(updated: true)       end     end     puts "*** Finished batch."   end end 
Read More

Sunday, April 17, 2016

`require': No such file to load — test_helper (LoadError)

Leave a Comment

I get the following error when I run my Rails application in production mode, but when I run my app in development mode it works fine. Can I use any gems in production mode?

`require': No such file to load -- test_helper (LoadError) 

The following is the full trace of the code:

 /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require': No such file to load -- test_helper (LoadError) from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `block in require' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require' from /home/nyros/Documents/Projects/DFL/Working/DFL/app/controllers/quarterly_export_statement_test.rb:1:in `<top (required)>' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `block in require' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:330:in `require_or_load' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:289:in `depend_on' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:207:in `require_dependency' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/engine.rb:465:in `block (2 levels) in eager_load!' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/engine.rb:464:in `each' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/engine.rb:464:in `block in eager_load!' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/engine.rb:462:in `each' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/engine.rb:462:in `eager_load!' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/engine.rb:347:in `eager_load!' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/application/finisher.rb:56:in `each' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/application/finisher.rb:56:in `block in <module:Finisher>' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/initializable.rb:30:in `instance_exec' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/initializable.rb:30:in `run' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/initializable.rb:55:in `block in run_initializers'   from /home/nyros/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/tsort.rb:345:in `each' from /home/nyros/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/tsort.rb:345:in `call' from /home/nyros/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component' from /home/nyros/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each' from /home/nyros/.rvm/rubies/ruby-2.2.0/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/initializable.rb:54:in `run_initializers' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/application.rb:215:in `initialize!' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/railtie/configurable.rb:30:in `method_missing' from /home/nyros/Documents/Projects/DFL/Working/DFL/config/environment.rb:5:in `<top (required)>' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `block in require' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:214:in `load_dependency' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/activesupport-4.0.2/lib/active_support/dependencies.rb:229:in `require' from /home/nyros/Documents/Projects/DFL/Working/DFL/config.ru:3:in `block in <main>' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/rack-1.5.5/lib/rack/builder.rb:55:in `instance_eval' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/rack-1.5.5/lib/rack/builder.rb:55:in `initialize' from /home/nyros/Documents/Projects/DFL/Working/DFL/config.ru:in `new' from /home/nyros/Documents/Projects/DFL/Working/DFL/config.ru:in `<main>' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/rack-1.5.5/lib/rack/builder.rb:49:in `eval' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/rack-1.5.5/lib/rack/builder.rb:49:in `new_from_string' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/rack-1.5.5/lib/rack/builder.rb:40:in `parse_file' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/rack-1.5.5/lib/rack/server.rb:277:in `build_app_and_options_from_config' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/rack-1.5.5/lib/rack/server.rb:199:in `app' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/commands/server.rb:48:in `app' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/rack-1.5.5/lib/rack/server.rb:314:in `wrapped_app' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/commands/server.rb:75:in `start' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/commands.rb:76:in `block in <top (required)>' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/commands.rb:71:in `tap' from /home/nyros/.rvm/gems/ruby-2.2.0@dfl/gems/railties-4.0.2/lib/rails/commands.rb:71:in `<top (required)>' from bin/rails:4:in `require' from bin/rails:4:in `<main>' 

1 Answers

Answers 1

You have a test, quarterly_export_statement_test.rb, in your app/controllers directory.

In production, Rails loads all classes eagerly, so it attempts to load your test. Your test does require 'test_helper'. The test directory, which contains test_helper, isn't in the load path in the production environment (good!), so that require fails.

To fix the problem, move the test to the test directory where it belongs, which appears to be /home/nyros/Documents/Projects/DFL/Working/DFL/test.

Read More