Deserialize more complex object with Rails 5 Posted: 14 Nov 2016 07:56 AM PST I'm creating a API with Rails 5 and using Mongo as storage. I'd like to have one single endpoint for creating and fetching (let's say /persons ). For example, let's say each person has posts and each post has comments. I'd like to have one single end point to create an entry in Mongo, passing a JSON like this when doing a POST: { "person" : { "name" : "a name", "posts" : [{ "comments" : [{}, ...] }, ...] } } For sake of clarity, I would like to have something like this in my Models: person.rb class Person include Mongoid::Document field :name, type: String embeds_many :posts end post.rb class Post include Mongoid::Document field :title, type: String embeds_many :comments embedded_in :person end comment.rb class Comment include Mongoid::Document field :title, type: String embedded_in :post end But I'm not able to deserialize neither save the embedded documents. How can I deserialize these kind of objects? I would like to access the data like person.posts[0].title . |
Factorygirl set has_many as nil Posted: 14 Nov 2016 07:55 AM PST I have a user factory that be default creates an association for user_document FactoryGirl.define do factory :user do |u| sequence(:first_name) {|n| "firstname-#{n}" } after(:create) do |user| create(:user_document, document_type: :address_proof, user: user) end end end I'd like to define a new factory for which the association user_document is null. How do I do this ? thanks |
Rails | Group by count of multiple columns Posted: 14 Nov 2016 07:48 AM PST I have a Country model with name, school and branch columns. I want to find out the unique number of schools and branches in a country. I expect the result to be in this format: {"India" => [25, 100]} //{Country => [No.of unique schools, No.of unique branches]} I want to calculate this value once in the controller (instead of doing something like below in the view). Country.all.each do |country| cs = Country.where(country: country).uniq.pluck(:school).count cb = Country.where(country: country).uniq.pluck(:branch).count end I am able to group one column by count like this Country.group(:school).order('count(school) desc').count // {"India"=>31, "USA"=> 50 } How can I do the same on multiple columns? Thanks in advance :) |
Pass a hash to ActiveRecord#save Posted: 14 Nov 2016 07:49 AM PST I have a an after_save callback on Scorecard class. In this callback I create and save an object in a different model BalanceLedger . I need to pass a message to this object being created in the after_save of Scorecard Is this possible? e.g. (where this is not valid but trying to get my point across) scorecard.total = new_total scorecard.save(message: 'This is an Admin correction') class Scorecard < ActiveRecord::Base after_save do BalanceLedger.create!(total: total, message: params[:message]) end |
if one object fails all objects rollback Posted: 14 Nov 2016 07:37 AM PST begin ActiveRecord::Base.transaction do installations.each do |installation| id = installation.id installation = current_user.installations.find_by(:id=> id) @ticket = installation.tickets.new(ticket_params) unless @ticket.save raise ActiveRecord::Rollback end end end redirect_to '/tickets', notice: "done" rescue ActiveRecord::Rollback render action: "new", notice: "problem" and return end Imagine that we have two tickets, the first ticket is valid and the second is invalid. In this code the first ticket will be saved. But I want to rollback all the tickets when one fail. How can I do that ? |
Rails xml to hash nested attr Posted: 14 Nov 2016 06:53 AM PST I have xml with nested attributes like <Flight AssociationID="F17462" Source="PN"> and <FareBasisCode PriceClass="FUN">X1/FUN</FareBasisCode> when i try convert it to hash with Hash.from_xml(my_xml) it gives me only first keys Flight without AssociationID I want to have ['Flight']['AssociationID'] etc Is it possible to do in such way? |
PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint Posted: 14 Nov 2016 06:37 AM PST I am working on ruby 2.3.1 and rails 3.2.1. I want to create new row of record in PostgreSQL db. I have created the database table with two column and primary key id and other column which accept string. def new_name label_name = LabelName.new(:id =>1, :label_name =>'testing' ) label_name.save() end If I pass the value of id , records get created otherwise I am getting the following error PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint. When I tried to create the record manually in PostgreSQL DB also I am getting the same error. Please help on how to solve this error. Thanks |
How to find out if the current date in rails is between a predefined date range (without the year) Posted: 14 Nov 2016 07:12 AM PST I currently have the following code in a helper within rails, which allows me to set a start date and end date and return true based on whether the current date is between the predefined range. My problem is with this code it'll only work for the current year, however I want to change it so it'll return true if the date is within the range, ignoring the year. def is_christmas? start_date = Date.parse('01-12-2016') end_date = Date.parse('25-12-2016') today = Date.today today.between?(start_date, end_date) end Any help with this would be greatly appreciated :) |
angular checklist-model throws No parent for group element Posted: 14 Nov 2016 06:21 AM PST I'm trying to use the checklist-model angular module, but it's raising this error which I can't figure out: No parent form group element found for input element <input type="checkbox" value="correlation" name="question[insights][enable][]" id="question_insights_enable_correlation" ng-model="checked" class="ng-scope ng-pristine ng-untouched ng-valid" bs-validation=""> The element is defined by rails: <%= insights_form.check_box("enable", {:multiple => true, 'checklist-model' => "model.enabled_insights"}, :correlation, nil) %> Which results in: <input checklist-model="model.enabled_insights" type="checkbox" value="correlation" name="insights[enable][]" id="insights_enable_correlation" /> If I remove the checklist-model attribute, the error goes away. I've googled the error but can't find any reference to anyone else experiencing it. |
Rails - How to show booking confirmation details Posted: 14 Nov 2016 06:49 AM PST I'm currently building an Events app using rails and I'm struggling a little with the booking confirmation side and how to show this to a user who has booked to attend an event. This is my code in the bookings_controller for the show / update actions and booking params - def show @event = Event.find(params[:event_id]) @booking = @event.bookings.new @booking = Booking.find_by(params[:booking_number]) end def update @event = Event.find(params[:event_id]) @booking = @event.bookings.new(booking_params) if @booking.update(booking_params) redirect_to event_booking_path , notice: "Booking was successfully updated!" else render 'new' end end private def booking_params params.require(:booking).permit(:stripe_token, :booking_number, :quantity, :event_id, :stripe_charge_id, :total_amount) end In my show views I have the following code for free bookings. In this instance I simply want to confirm (at this stage) the event title, quantity of spaces they've requested and the unique booking number - <h1>Hi there</h1> <p>You have placed a booking on <%= @event.title %>.</p> <p>You have reserved <%= @booking.quantity %> spaces for this event.</p> <p>Your booking number is <%= @booking.booking_number %></p> <p>We hope you have a wonderful time. Enjoy!</p> At the moment, when I perform a test booking I get this in my views - So, basically, the specific details for quantity and number are not showing. I'm sure this is something so obvious but I'm failing to spot it. What am I missing? |
Cocoon fields are not affected by JS Posted: 14 Nov 2016 07:54 AM PST I'm using cocoon to create quotes for my users. A Quote has_many Expense Categories , and each Expense Category has many Expenses I added some JS, so that everytime my user changes the value of an expense, it updates the total price in another input, but this doesn't work with the newly created inputs. I made sure they all had the same classes (.expense .price-input) I tried with this little piece of code: $('.expense .price-input').keyup(function () { alert('OK'); }); When I type something in the existing inputs, OK is displayed. When I create an expense, typing something in the newly created input won't trigger it. Is there something to initialize? |
How to push key and value to an empty hash with a loop in Ruby on rails Posted: 14 Nov 2016 07:26 AM PST I want to use Bing search results for my webpage. To use their json data I found this solution: new_bing_results = bing_results[0][:Web] result = { } result[:title] = new_bing_results[0][:Title] result[:description] = new_bing_results[0][:Description] result[:url] = new_bing_results[0][:Url] result[:display_url] = new_bing_results[0][:DisplayUrl] result[:title1] = new_bing_results [1][:Title] result[:description1] = new_bing_results [1][:Description] result[:url1] = new_bing_results [1][:Url] result[:display_url1] = new_bing_results [1][:DisplayUrl] result[:title2] = new_bing_results [2][:Title] result[:description2] = new_bing_results [2][:Description] result[:url2] = new_bing_results [2][:Url] result[:display_url2] = new_bing_results [2][:DisplayUrl] .... result How can I create a loop that is doing the same thing 50 times without having to repeat the same code. I tried this but only get errors: new_bing_results = bing_results[0][:Web] $i = 0 $num = 50 result2 = {} while $i < $num do result[:title$i] = new_bing_results[$i][:Title] ...... end result The problem is that I do not find a solution for adding my $i number to the key result[:title] as in the value new_bing_results[$i][:Title] |
How to store environment variables with Figaro on a non Heroku server? Posted: 14 Nov 2016 07:10 AM PST I have a Rails 5 app, and I'm trying to store my environment variables on a non Heroku server. Therefore I created a config/application.yml file with my environment variables on the production server. However, when I try to deploy my Rails app, the deployment fails because the environment variables can't be accessed. Am I missing something? |
Cannot render cart on one page Posted: 14 Nov 2016 05:54 AM PST So I am trying to render my cart on my tickets page, but it isn't working. It is working on every other page, but not this one. _cart.html.erb: <div class="modal-content"> <% if current_page?(controller: 'orders', action: 'new') == false %> <h4>Your Cart</h4> <% end %> <ul class="collection"> <%= render(cart.line_items) %> <li class="collection-item"><span style="float:right"></span>Total: <%= number_to_currency(cart.total_price) %></li> </ul> </div> <% if current_page?(controller: 'orders', action: 'new') == false %> <div class="modal-footer"> <a href="/checkout" class="modal-action modal-close waves-effect waves-green btn-flat">Checkout</a><%= button_to 'Empty cart', cart, method: :delete, class: "modal-action modal-close waves-effect waves-green btn-flat", data: { confirm: 'Are you sure?' } %> </div> <% end %> _line_item.html.erb: <li class="collection-item"><%= line_item.quantity %> × <%= TicketType.find(line_item.tickettype_id).name %> for <%= Movie.find(line_item.showtime.movie_id).title %> @ <%= line_item.showtime.time.strftime("%I:%M %p") %> - <%= Theater.find(line_item.showtime.theater_id).name %> - <%= number_to_currency(line_item.total_price) %></li> When it trys to render the line_item part, it says that line_item.tickettype_id is nil, which for some reason when rendered on tickets.html.erb it is, but on the rest of the pages it works correctly. tickets.html.erb: <div class="container"> <br> <h3><%= @movie.title %> at <%= @showtime.time.strftime("%I:%M %p") %> on <%= @showtime.date.strftime('%a %b %d') %></h3> <div class="row"> <div class="col s4 theater-info"> <img src="<%= image_url(@movie.image_url) %>" height="350px" style="margin-left:50%;transform: translateX(-50%)" class="materialboxed"> <h5><%= @movie.title %> <span class="new red badge" data-badge-caption=""><%= @movie.rating %></span><span class="new red badge" data-badge-caption=""><%= @movie.runtime %></span></h5> <p>Description: <%= @movie.description %></p> <p>Actors: <%= @movie.actors %></p> <p>Genre: <%= @movie.genre %></p> </div> <div class="col s5 more-info"> <%= render "tickets" %> </div> <div class="col s3 showtime-info"> <div id="cart"> <%= render @cart %> </div> </div> </div> </div> <p id="notice"><%= notice %></p> _tickets.html.erb (since its rendered on tickets.html.erb): <% for ticketType in selectTickets(@showtime.theater_id)%> <div class="card-panel red"> <div class="row"> <span><%= ticketType.name %> </span> <span>(<%= ticketType.description %>) </span> <span><%= number_to_currency(ticketType.price) %> </span> <%= form_for @line_itemssss, :url => line_items_path, remote: true do |f| %> <%= f.select :quantity, options_for_select([[0,0], [1,1], [2,2], [3,3], [4,4], [5,5], [6,6], [7,7], [8.8], [9,9], [10,10]]) %> <%= f.hidden_field :tickettype_id, :value => ticketType.id %> <%= f.hidden_field :showtime_id, :value => @showtime.id %> <%= f.submit %> <% end %> <%= button_to('Add to Cart', line_items_path(tickettype_id: ticketType.id, showtime_id: @showtime.id, quantity: 1), remote: true, :class => "btn waves-effect waves-light") %> </div></div> <% end %> pages_controller.rb (for tickets.html.erb): class PagesController < ApplicationController include SessionsHelper include CurrentCart before_action :set_cart def tickets @showtime = Showtime.find(params[:id]) @movie = Movie.find(@showtime.movie_id) @line_itemssss = @cart.add_ticket(params[:showtime_id], params[:tickettype_id], params[:quantity]) end end Full trace of error: activerecord (5.0.0.1) lib/active_record/core.rb:173:in `find' app/views/line_items/_line_item.html.erb:1:in `_app_views_line_items__line_item_html_erb___1395406200177303248_69961294673900' actionview (5.0.0.1) lib/action_view/template.rb:158:in `block in render' activesupport (5.0.0.1) lib/active_support/notifications.rb:166:in `instrument' actionview (5.0.0.1) lib/action_view/template.rb:348:in `instrument' actionview (5.0.0.1) lib/action_view/template.rb:156:in `render' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:438:in `block in collection_with_template' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:434:in `map' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:434:in `collection_with_template' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:327:in `block (2 levels) in render_collection' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer/collection_caching.rb:13:in `cache_collection_render' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:326:in `block in render_collection' actionview (5.0.0.1) lib/action_view/renderer/abstract_renderer.rb:42:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument' actionview (5.0.0.1) lib/action_view/renderer/abstract_renderer.rb:41:in `instrument' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:319:in `render_collection' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:308:in `render' actionview (5.0.0.1) lib/action_view/renderer/renderer.rb:47:in `render_partial' actionview (5.0.0.1) lib/action_view/helpers/rendering_helper.rb:35:in `render' app/views/carts/_cart.html.erb:6:in `_app_views_carts__cart_html_erb___847962542900355211_69961295413560' actionview (5.0.0.1) lib/action_view/template.rb:158:in `block in render' activesupport (5.0.0.1) lib/active_support/notifications.rb:166:in `instrument' actionview (5.0.0.1) lib/action_view/template.rb:348:in `instrument' actionview (5.0.0.1) lib/action_view/template.rb:156:in `render' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:343:in `render_partial' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:311:in `block in render' actionview (5.0.0.1) lib/action_view/renderer/abstract_renderer.rb:42:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument' actionview (5.0.0.1) lib/action_view/renderer/abstract_renderer.rb:41:in `instrument' actionview (5.0.0.1) lib/action_view/renderer/partial_renderer.rb:310:in `render' actionview (5.0.0.1) lib/action_view/renderer/renderer.rb:47:in `render_partial' actionview (5.0.0.1) lib/action_view/helpers/rendering_helper.rb:35:in `render' app/views/pages/tickets.html.erb:19:in `_app_views_pages_tickets_html_erb__2769498277689600672_69961298930760' actionview (5.0.0.1) lib/action_view/template.rb:158:in `block in render' activesupport (5.0.0.1) lib/active_support/notifications.rb:166:in `instrument' actionview (5.0.0.1) lib/action_view/template.rb:348:in `instrument' actionview (5.0.0.1) lib/action_view/template.rb:156:in `render' actionview (5.0.0.1) lib/action_view/renderer/template_renderer.rb:54:in `block (2 levels) in render_template' actionview (5.0.0.1) lib/action_view/renderer/abstract_renderer.rb:42:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument' actionview (5.0.0.1) lib/action_view/renderer/abstract_renderer.rb:41:in `instrument' actionview (5.0.0.1) lib/action_view/renderer/template_renderer.rb:53:in `block in render_template' actionview (5.0.0.1) lib/action_view/renderer/template_renderer.rb:61:in `render_with_layout' actionview (5.0.0.1) lib/action_view/renderer/template_renderer.rb:52:in `render_template' actionview (5.0.0.1) lib/action_view/renderer/template_renderer.rb:14:in `render' actionview (5.0.0.1) lib/action_view/renderer/renderer.rb:42:in `render_template' actionview (5.0.0.1) lib/action_view/renderer/renderer.rb:23:in `render' actionview (5.0.0.1) lib/action_view/rendering.rb:103:in `_render_template' actionpack (5.0.0.1) lib/action_controller/metal/streaming.rb:217:in `_render_template' actionview (5.0.0.1) lib/action_view/rendering.rb:83:in `render_to_body' actionpack (5.0.0.1) lib/action_controller/metal/rendering.rb:52:in `render_to_body' actionpack (5.0.0.1) lib/action_controller/metal/renderers.rb:144:in `render_to_body' actionpack (5.0.0.1) lib/abstract_controller/rendering.rb:26:in `render' actionpack (5.0.0.1) lib/action_controller/metal/rendering.rb:36:in `render' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:44:in `block (2 levels) in render' activesupport (5.0.0.1) lib/active_support/core_ext/benchmark.rb:12:in `block in ms' /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/benchmark.rb:308:in `realtime' activesupport (5.0.0.1) lib/active_support/core_ext/benchmark.rb:12:in `ms' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:44:in `block in render' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:87:in `cleanup_view_runtime' activerecord (5.0.0.1) lib/active_record/railties/controller_runtime.rb:25:in `cleanup_view_runtime' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:43:in `render' actionpack (5.0.0.1) lib/action_controller/metal/implicit_render.rb:36:in `default_render' actionpack (5.0.0.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `block in send_action' actionpack (5.0.0.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `tap' actionpack (5.0.0.1) lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action' actionpack (5.0.0.1) lib/abstract_controller/base.rb:188:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/rendering.rb:30:in `process_action' actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:20:in `block in process_action' activesupport (5.0.0.1) lib/active_support/callbacks.rb:126:in `call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:506:in `block (2 levels) in compile' activesupport (5.0.0.1) lib/active_support/callbacks.rb:455:in `call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:101:in `__run_callbacks__' activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks' activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks' actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:19:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/rescue.rb:20:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/params_wrapper.rb:248:in `process_action' activerecord (5.0.0.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action' actionpack (5.0.0.1) lib/abstract_controller/base.rb:126:in `process' actionview (5.0.0.1) lib/action_view/rendering.rb:30:in `process' actionpack (5.0.0.1) lib/action_controller/metal.rb:190:in `dispatch' actionpack (5.0.0.1) lib/action_controller/metal.rb:262:in `dispatch' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:50:in `dispatch' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:32:in `serve' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `each' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `serve' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call' rack (2.0.1) lib/rack/etag.rb:25:in `call' rack (2.0.1) lib/rack/conditional_get.rb:25:in `call' rack (2.0.1) lib/rack/head.rb:12:in `call' rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context' rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call' activerecord (5.0.0.1) lib/active_record/migration.rb:552:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__' activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks' activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks' actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call' web-console (3.1.1) lib/web_console/middleware.rb:131:in `call_app' web-console (3.1.1) lib/web_console/middleware.rb:28:in `block in call' web-console (3.1.1) lib/web_console/middleware.rb:18:in `catch' web-console (3.1.1) lib/web_console/middleware.rb:18:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call' railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app' railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged' railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call' sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call' rack (2.0.1) lib/rack/method_override.rb:22:in `call' rack (2.0.1) lib/rack/runtime.rb:22:in `call' activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call' rack (2.0.1) lib/rack/sendfile.rb:111:in `call' railties (5.0.0.1) lib/rails/engine.rb:522:in `call' puma (3.4.0) lib/puma/configuration.rb:224:in `call' puma (3.4.0) lib/puma/server.rb:569:in `handle_request' puma (3.4.0) lib/puma/server.rb:406:in `process_client' puma (3.4.0) lib/puma/server.rb:271:in `block in run' puma (3.4.0) lib/puma/thread_pool.rb:114:in `block in spawn_thread' What is causing the line_item not to be rendered correctly only on one page? How would one figure this out? |
Rails where condition on has_and_belongs_to_many association Posted: 14 Nov 2016 05:56 AM PST I have a has_and_belongs_to_many association between product and supplier. join table is products_suppliers . I am trying to create dependent selects in a form so that when I select a supplier, in the product dropdown only corresponding products appears. I'm having a problem with the where conditions. If I was in a situation where product belongs_to supplier I would do: @products = Product.where("supplier_id = ?", params[:supplier_id]) How do I achieve the same in a has_and_belongs_to_many association? |
Delete 1-to-1 association in Rails Posted: 14 Nov 2016 05:31 AM PST I have Person-has-one-Address in Rails. the has_one association is set on Person , while belongs_to is set to Address . I tried to delete this association and this worked: person.address = nil which generated a corresponding UPDATE statement. However, if I try to do the same from the child: address.person = nil I get nothing. I tried to do address.save and no SQL was generated. I also tried address.person_id = nil and still nothing! I'm using Rails 5 and heard there's some change that prevents this, just not sure what it is. |
Connect rails with sql server 2012 remotly Posted: 14 Nov 2016 07:15 AM PST i have Linux fedora installed on machine and also i am working with rails project and i have SQL server 2012 on another machine .... i want to connect rails with SQL server 2012 remotely. How can i do this ?? |
Rails render_to_string using wrong format Posted: 14 Nov 2016 05:20 AM PST I am encountering a problem with render_to_string using Rails 3.2.18 in which the function is trying to render the wrong view format despite its :formats option being correctly set (so for example rendering the kml view when :formats is set to text ). TL-DR version : If I call render_to_string('foos/bar', formats: 'text', layout: false) and then render_to_string('foos/bar', formats: 'json', layout: false) , the later renders bar.text instead of bar.json Long version : I have a FoosControler that uses render_to_text when its bar action is called. bar can respond to three formats : text , json and kml . Under my views, I have the three corresponding files bar.text.erb , bar.json.erb and bar.kml.erb . I also have three different tests, in which the controller is instantiated and the output of bar is tested for the different formats (so I am calling FoosControler.new.bar(format) ). If I run each of those tests independently, I have no problems at all. So : render_to_string('foos/bar', formats: 'text', layout: false) # => renders bar.text.erb render_to_string('foos/bar', formats: 'json', layout: false) # => renders bar.json.erb render_to_string('foos/bar', formats: 'kml', layout: false) # => renders bar.kml.erb The problems start if I have more than one of these in my test suite. What happens is the following : render_to_string('foos/bar', formats: 'json', layout: false) # => renders bar.json.erb render_to_string('foos/bar', formats: 'text', layout: false) # => renders bar.text.erb render_to_string('foos/bar', formats: 'json', layout: false) # => renders bar.text.erb instead of bar.json.erb ! From the moment I rendered bar.text.erb , any call to render_to_string with the json format renders bar.text.erb instead of bar.json.erb like it is supposed to. The same happens between kml and txt : render_to_string('foos/bar', formats: 'text', layout: false) # => renders bar.text.erb render_to_string('foos/bar', formats: 'kml', layout: false) # => renders bar.kml.erb render_to_string('foos/bar', formats: 'text', layout: false) # => renders bar.kml.erb instead of bar.text.erb ! I can't seem to understand why this problem happens, as the problem isn't linked to the views - they all exist and can be rendered as shown before. Even stranger, everything works if I force the format in the render instead of using the :format parameter : render_to_string('foos/bar.text', layout: false) # => renders bar.text.erb render_to_string('foos/bar.kml', layout: false) # => renders bar.kml.erb render_to_string('foos/bar.text', layout: false) # => renders bar.text.erb like it is supposed to A few other precisions : - It doesn't matter whether I use formats: '<format>' or formats: ['<format>'] - The problem happens regardless of whether I use the different render_to_string inside the same controller using a breakpoint or whether I simply call the sequence of FoosController.new.bar(format) in the test, so the following two give the same result : FoosController.new.bar render_to_string('foos/bar', formats: 'kml', layout: false) # => renders bar.kml.erb render_to_string('foos/bar', formats: 'text', layout: false) # => renders bar.kml.erb instead of bar.text.erb ! FoosController.new.bar('kml') # => renders bar.kml.erb FoosController.new.bar('text') # => renders bar.kml.erb instead of bar.text.erb ! Any idea what can cause this unwanted behavior ? Forcing the format like I did seems to patch the issue, but I'd still want to know what exactly is going on. |
Ruby on Rails: NoMethodError undefined method `get_yaml' for String Posted: 14 Nov 2016 04:11 AM PST I tried to deploy a non public project but sometimes when tried to use report pages (based on prawn) I have this problem: NoMethodError (undefined method `get_yaml' for #<String:0x7fdecffd3738>): The piece of code is: report_content = report.draw(report_content.get_yaml) Someone know: where are get_yaml come from? Thanks. |
Algoliasearch-Rails : Index variations of a single record Posted: 14 Nov 2016 05:05 AM PST I would like to index differents variations of the same record, just like explained in this doc: How should I do this with the Algoliasearch-Rails gem ? I can't find any doc or example about this. More details: I have a model Card which embeds_many Locations (Mongoid). For each location of this card, I would like to add a new record in my Algolia index and then Group the result by Card's slug. |
in_groups_of with fields_for in Rails Posted: 14 Nov 2016 05:17 AM PST I've some fields in a form that I want to group by series of 3. Right now it looks like this <!-- Variant boxes --> <div class="row form-group"> <%= f.fields_for :options do |field_option| %> <div class="col-md-4"> <%= render partial: "shopkeeper/products/variants/index/form/variant_box", :locals => {:form => field_option} %> </div> <% end %> </div> For aesthetic reason, every 3 field_option I want to be able to add a <div class='row'> so I don't break my grid system. I know the method in_groups_of(3, false) which I use when I simply want to show data, but here we are in a special context of form therefore I'm out of solution ... What's the easiest way to achieve this ? |
linkedin share pop open different image on pop up than original one to share Posted: 14 Nov 2016 03:33 AM PST in my blog show page = content_for :og_tag_blog_share do %meta{:property => "og:title", :content => "#{@blog.title}"}/ %meta{:property => "og:description", :content => "#{@blog.description}"}/ %meta{:property => "og:image",:content => "#{@blog.blog_image.url(:thumb)}"}/ %a{:href => "javascript:postToLinkedIn('#{@blog.title}','#{strip_tags(@blog.description).truncate(400)}','#{@blog.blog_image.url}','#{redirect_url}')"} %img{:alt => "Linkedin", :src => "/assets/social-02.png"}/ in js file function postToLinkedIn(title, summary, imageurl, U){ var articleUrl = encodeURIComponent(U); var articleTitle = encodeURIComponent(title); var articleSummary = encodeURIComponent(summary); var imageUrl = encodeURIComponent(imageurl); var goto = 'http://www.linkedin.com/shareArticle?mini=true'+ '&url='+articleUrl+ '&title='+articleTitle+ '&summary='+articleSummary; window.open(goto, "LinkedIn", "width=660,height=400,scrollbars=no;resizable=no"); } and in application.html.haml = content_for?(:og_tag_blog_share) ? yield(:og_tag_blog_share) : '' but on sharing pop up i see different image to share than original one. i am able to see the meta tag on share page by inspecting page. what will be the reason of different image.? |
Action Mailer not respecting default url options Posted: 14 Nov 2016 02:54 AM PST I'd like to send an email with some links with my Rails app. The links point to specific pages in my app. Also I'd like to use ActiveMailer for Devise's password recovery feature. The problem is that the URLs Rails is generating are not respecting the default URL Host set in my production environment. My code here: config/environment/production.rb config.action_mailer.default_url_options = { host: 'example.com' } views/post_mailer/new_post.html.erb <%= link_to 'go to new post here', url_for(@post)%></p> URLs generated in my email links http://email.mail.example.com/etc... As you can see 'email.mail' is appended at the beginning of the URL whilst I'd have expected my URL to be: http://example.com/etc... My site, therefore, can't be reached when a user clicks the links (they are sent to http://email.mail.example/etc that doesn't exist). I've tried: 1. Using different helpers to generate the links <%= link_to 'new post here', posts_url %> <%= link_to 'new post here', post_url(@post) %> 2. Defining the host in the link itself and not in production.rb <%= link_to 'new post here', post_url(@post, host: 'example.com') %> 3. Generating a link without any helpers <a href= <%= "www.example.com/posts/#{@post.id}" %> > post here </a> 4. Even using RegEx to get rid of 'email.mail' <%= link_to 'new post here', post_url(@post).gsub('email.mail.','') %> Nothing seems to work, in all cases 'email.mail' is appended, and I don't seem to be finding any relevant solutions in the web. I'd highly appreciate your help, even it is only pointing me to the right sources. Thanks. |
Separating front end from the isomorphic Ruby on Rails web application. Posted: 14 Nov 2016 02:48 AM PST We have our web application built completely on Ruby on Rails. The front end is tightly coupled with the backend. We are in a stage where we want to gradually start separating our frontend from the backend. We want to go ReactJS way with the UI part and we want to follow the waterfall model for the transition. We have two options: Use gem called react-rails, and build new components in React. Slowly start converting existing components into React components. Once we have all components converted into React components, take out every React component, separate complete frontend and host it somewhere else. Host ReactJS somewhere else. Gradually start converting each component to React component, move it to new hosted place and remove them from Rails. The only catch is, React components will be located at a different location than where Rails is. While navigating within the app, it could give a feel of navigating to a different website. Please share your experience and guide us on which way should we proceed. Our end goal is to have the complete front end in ReactJS and backend on Rails. They communicate via APIs, completely removing coupling between frontend and backend. Thanks |
Kaminari syntax error, unexpected '=' Posted: 14 Nov 2016 03:10 AM PST I am using Kaminari paginator and I got this error. I followed the instructions here! SyntaxError (../ruby/2.3.0/gems/kaminari-0.17.0/app/views/kaminari/_paginator.html.erb:1: syntax error, unexpected '=' ...buffer = @output_buffer;class = class = local_assigns[:class... ... Please take a look at my controller and views This is my controller def show @asset_location = AssetLocation.find(params[:id]) if @asset_location.asset_location_type.name == 'unit_section' redirect_to :action => :edit, :id => params[:id] else # paginate sub-locations page_num = paginator_page_number(AssetLocation, params[:id]) per_page = paginator_per_page(AssetLocation, params[:id]) @asset_locations = @asset_location.sub_locations.page(page_num).per(per_page) if @asset_locations.empty? and page_num > 1 page_num -= 1 @asset_locations = @asset_location.sub_locations.page(page_num).per(per_page) end session["asset_location_#{params[:id]}".to_sym][:page] = page_num respond_to do |format| format.html format.js end end ..and this is my view <tfoot> <tr class="body-bg-color"> <td colspan="8"> <!-- pagination component here --> <div class="row-fluid row-fluid-no-margin" id="bottom-paginator"> <%= paginate @asset_locations, :params => { :action => 'show', :id => @asset_location.id }, class: 'pagination pull-right' %> </div> </td> </tr> </tfoot> I don't know what is the problem here. Can you help me guys? Thanks! |
Create postgres index for table with inner join in RubyOnRails Posted: 14 Nov 2016 07:09 AM PST I have an app based on RubyOnRails 4.0. I have two models: Stores and Products. There are about 1.5 million products in the system making it quite slow if I do not use indices properly. Some basic info - Store has_many Products
- Store.affiliate_type_id is used where 1=Affiliated 2=Not affiliated
- Products have attributes like "category_connection_id" (integer) and "is_available" (boolean)
In FeededProduct model: scope :affiliated, -> { joins(:store).where("stores.affiliate_type_id = 1") } This query takes about 500ms which basically interrupts the website: FeededProduct.where(:is_available => true).affiliated.where(:category_connection_id => @feeded_product.category_connection_id) Corresponding postgresql: FeededProduct Load (481.4ms) SELECT "feeded_products".* FROM "feeded_products" INNER JOIN "stores" ON "stores"."id" = "feeded_products"."store_id" WHERE "feeded_products"."is_available" = 't' AND "feeded_products"."category_connection_id" = 345 AND (stores.affiliate_type_id = 1) Update. Postgresql EXPLAIN: QUERY PLAN ------------------------------------------------------------------------------------------------- Hash Join (cost=477.63..49176.17 rows=21240 width=1084) Hash Cond: (feeded_products.store_id = stores.id) -> Bitmap Heap Scan on feeded_products (cost=377.17..48983.06 rows=38580 width=1084) Recheck Cond: (category_connection_id = 5923) Filter: is_available -> Bitmap Index Scan on cc_w_store_index_on_fp (cost=0.00..375.25 rows=38580 width=0) Index Cond: ((category_connection_id = 5923) AND (is_available = true)) -> Hash (cost=98.87..98.87 rows=452 width=4) -> Seq Scan on stores (cost=0.00..98.87 rows=452 width=4) Filter: (affiliate_type_id = 1) (10 rows) Question: How can I create an index that will take the inner join into consideration and make this faster? |
CSS file to include only in single page Rails not working on Server Posted: 14 Nov 2016 02:54 AM PST I have included a css file for styling of pdf. I can't add this in tree as it will override styles, used on on other pages. So I include the pdf.css is app/assets/stylesheets. and in head of view i.e pdf_format.slim I added link href='/assets/pdf.css' rel='stylesheet' type='text/css' It works ok on local machine but on server it seems that it didn't found css. How to give path to css file in such case. |
ActiveRecord's configuration error - ActiveRecord::AdapterNotSpecified Posted: 14 Nov 2016 04:27 AM PST Why doesn't the program run? list.rb require 'active_record' require 'yaml' ActiveRecord::Base.configurations = YAML.load_file('./database.yml') ActiveRecord::Base.establish_connection('development') class Student < ActiveRecord::Base end student = Student.find('123') puts student.id puts student.name database.yml development: adapter: sqlite3 database: list list.db sqlite> select * from students; 123|foo|foo@email.com error ../activerecord-5.0.0.1/lib/active_record/connection_adapters/connection_specification.rb:170:in `spec': database configuration does not specify adapter (ActiveRecord::AdapterNotSpecified) |
Rails Mailer - Can I specify a different subject line for reply? Posted: 14 Nov 2016 02:26 AM PST Is there a way to specify a new subject, the same way that I can specify a different reply-to address? For example, the transactional email I'm sending from my rails app is from "hello@my-app.com" and the subject line is "Someone Likes Your Product!" When the user receives the email I'd like them to respond to a specific email (which I know how to do) and the subject should be changed from "Re: Someone Likes Your Product!" to "Thanks for liking my product!" (In case this helps, I'm using Sparkpost as the email service) Is this even possible? Thanks in advance! |
#as_json includes does not call as_json on the assoc Posted: 14 Nov 2016 02:05 AM PST I have a User(id, name, something_secret, created_at, updated_at) and a Company(id, name, something_secret, created_at, updated_at) Model: class Company def as_json(options = {}) opts = { only: [:id, :name] }.merge(options) super(opts) end end class User def as_json(options = {}) opts = { only: [:id, :name], includes: [:company] }.merge(options) super(opts) end end If I call company.as_json , then everything is fine, I get: { id: 1, name: "Name" } HOWEVER, if I call user.as_json , then it includes ALL of company stuff { id: 1, name: "Jim", company: { id: 1, name: "Name", something_secret: "super secret", created_at: "2016-11-12 13:03:07", updated_at: "2016-11-12 13:03:07" } } This seems like it should call #as_json on the company, but it doesn't. WHY doesn't it? and HOW can I get it to do so? Thanks |
Really nice blog post.provided a helpful information.I hope that you will post more updates like this Ruby on Rails Online Course India
ReplyDelete