XIO

xWire

Posts from every feed QUEST has found across the web — blogs, news, podcasts, channels and more.

Ruby on Rails Discussions - Latest posts

Latest posts

What is a good database structure for products, orders, payments, and inventory in a Rails POS application?

I agree with this approach. Keeping transactional data separate from the current inventory state makes the POS system easier to maintain and scale. Storing the actual sale price in order_items is especially important because product prices can change over time. I also like the idea of using stock movements for purchases, sales, returns, and adjustments. It provides a clear audit trail and makes inventory discrepancies much easier to investigate. Using database transactions for the sale process…

[Newbie] ActiveRecord: Calculate maximum of calculated column

Max Mustermann: Hi there, I recently started learning Ruby on Rails. I decided to learn Rails by programming some kind of small statistic application where I can document the fuel consumption of my car - i.e. everytime I’m at the gas station I log price and amount of the gas refuled and the distance travelled since the last refuelling. One of my models looks like this: # start class Refuelling < ActiveRecord::Base belongs_to :car def consumption liter/kilometer * 100 end def liter_price…

What is a good database structure for products, orders, payments, and inventory in a Rails POS application?

I’d keep the POS schema fairly normalized and separate the transactional records from the current inventory state. A common structure would be products, orders, order_items, payments, and an inventory table or stock-movement table. order_items should store the product, quantity, and the price actually charged at the time of sale, rather than relying on the product’s current price. For inventory, I’d prefer recording stock movements (purchases, sales, returns, adjustments) so you have an audit…

Wrap all handlers for `rescue_from` inside block

I’d keep I18n.with_locale, but call the original handler with instance_exec inside it. Yielding a previously captured block does not change that block’s self; Rails changes the context of your outer wrapper, not of the original handler passed through &. For the block-only helper in your example: def self.rescue_from_with_locale(*exceptions, &handler) rescue_from(*exceptions) do |exception| locale = params[:locale] || I18n.default_locale I18n.with_locale(locale) do if handler.arity == 0…

How do these 'proxy' types work exactly?

The behavior comes from Rails’ delegation/proxy layer rather than content actually having every method as a normal instance method. ActiveStorage::Attached::One exposes attachment/blob-related behavior through generated delegation methods, so methods/inspect can be misleading compared with what you can actually call at runtime. For Steep and IDE support, I’d look at the Rails/RBS signatures for ActiveStorage::Attached::One and the generated delegation rather than trying to infer the API from…

Single table inheritance opt-in

I agree that it is weird that STI is automatically enabled once there is a type column and it would less surprising for it to be opt-in. It feels like kind of an inconsistency, since the presence of a user_id column also does not automatically define belongs_to :user This is especially annoying when dealing with tables not under your control or when defining ActiveRecord classes inside migrations (since data migration must often skip callbacks and other business logic defined in the original…

Proposal: Action Cable should accept a WebSocket handshake with no Origin header, as Action Controller does

What happens today Action Cable rejects any WebSocket handshake whose Origin header is missing. On 8.1.3 and on main the check is: # actioncable/lib/action_cable/server/base.rb (main) def allow_request_origin?(env) return true if config.disable_request_forgery_protection request = ActionDispatch::Request.new(env) proto = request.ssl? ? "https" : "http" if config.allow_same_origin_as_host && env["HTTP_ORIGIN"] == "#{proto}://#{request.host_with_port}" true elsif…

Wrap all handlers for `rescue_from` inside block

I am trying to output localized messages to the user inside all rescue_from blocks, but can’t get it to work. I want to avoid the boilerplate of wrapping each handler inside a I18n.with_locale block manually. My general approach is this: class ApplicationController < ActionController::Base def self.rescue_from_with_locale(*, **, &) self.rescue_from(*, **) { I18n.with_locale(params[:locale], &) } end rescue_from_with_locale Error1 do render(plain: t("error1_happened")) end…

How do these 'proxy' types work exactly?

It’s delegate_missing_to, twice. In activestorage 8.1: # lib/active_storage/attached/one.rb delegate_missing_to :attachment, allow_nil: true # app/models/active_storage/attachment.rb delegate_missing_to :blob So anything Attached::One doesn’t define itself goes to the ActiveStorage::Attachment record, and anything the attachment doesn’t define goes on to its ActiveStorage::Blob. That’s why content.byte_size, content.filename, content.content_type etc. all work from the top. delegate_missing_to…

What is the best way to optimize slow ActiveRecord queries in a Rails application?

If you are experiencing slow performance then there are some common pitfalls, like the notorious “N+1” problem when showing a list of things. What this means is that there is 1 overall query to bring back a collection of items, and then N more queries that are pulling individual values, with N additional separate queries happening in order to get detail for each object you’re displaying. If you take a look at the terminal window while your app is loading a slow page, do you see a long list of…

Responsive images (img srcset) with ActiveStorage

The helper looks reasonable to me. I’d probably keep the actual list of widths and sizes outside Active Storage, though, since those are usually determined by the application layout. If the number of responsive sizes starts growing, another option is to keep only the original in Active Storage and move the resizing to a separate image processor. The srcset helper would then generate a URL for each width, while a CDN or reverse proxy could cache the processed results. That avoids managing an…

ActiveStorage - has_one_attached ... analyze: false

I’d avoid setting analyzed: true directly if possible. It prevents the job, but it also makes the blob look like it was actually analyzed, which could get confusing if other code later relies on that state. A no-op analyzer for this class of files feels cleaner if the main goal is to avoid downloading large videos for metadata you don’t use. The analysis job may still get enqueued, but it should do almost no work. If the requirement is specifically to never enqueue analysis for this attachment,…

Single table inheritance opt-in

Ngan: Nowadays, I feel like I don’t use Single Table Inheritance anymore. When I need this sort of paradigm, I reach for ActiveRecord::DelegatedType. Additionally, I’ve always found it annoying that I can’t easily use a column named type. For example, given a model called Food, I’d have to name it something like food_type, which feels pretty ugly. So lately, I’ve been doing: I agree that ActiveRecord::DelegatedType can be a cleaner option when you need this kind of polymorphic structure without…

How can I safely handle file uploads with Active Storage?

Lorin Thwaits: For fault tolerance, set up ActiveStorage mirroring. (That article describes how to add an additional service once you have one set up — and in your case to have good assurance not to lose uploaded content then just maintain one or more mirrors on differing services.) ActiveStorage mirroring seems like a practical approach for improving fault tolerance and reducing the risk of losing uploaded files. Using different storage providers for the mirrors also makes sense because it…

Single table inheritance opt-in

Yeah, I can do that, but then everyone who joins the company/project has to find out we do this non-default thing. Just want to make it clear that I’m not complaining about the difficulty of the workaround. I’m just proposing we revisit the default given the alternative (delegated types) is opt-in. And, I’ve noticed less and less usage of STI these days due to its foot gun with autoload.

Active Storage: How to create "named variants" that are cropped by user-supplied coordinates

I’d probably store the crop coordinates separately, like suggested above, and keep the original image unchanged. For a few fixed avatar sizes, I would still let Active Storage handle the variants. If the crop can change or the application starts needing a lot of different output sizes, another option is to move the transformation itself into a separate image processor. imgproxy is one self-hosted option for that. It can crop the original first and then resize the result on request: imgproxy.net…

Proposal: Enhance the DirectUpload JS API to support more useful custom blob names (like the ActiveStorage::Attached::*attach(:key) argument)

I like the idea of readable prefixes for debugging, but I would be cautious about making the final storage key entirely client-controlled.I think a useful middle ground would be to let the client provide some logical information, such as a project or desired filename, while Rails constructs the actual key and appends a server-generated unique value. That would preserve readable paths without making the key itself something the application has to trust for uniqueness or authorization. I would…

Single table inheritance opt-in

Ngan: class Food < ApplicationRecord self.inheritance_column = nil end Why not to put it into ApplicationRecord once per project and forget about it? Doesn’t it inherit properly? You could go further and craft your own application template for that if you make a lot of projects and don’t want to put the line into every project manually.

Single table inheritance opt-in

Nowadays, I feel like I don’t use Single Table Inheritance anymore. When I need this sort of paradigm, I reach for ActiveRecord::DelegatedType. Additionally, I’ve always found it annoying that I can’t easily use a column named type. For example, given a model called Food, I’d have to name it something like food_type, which feels pretty ugly. So lately, I’ve been doing: class Food < ApplicationRecord self.inheritance_column = nil end Just so I can use type as the column name. What does everyone…

Heroku alternatives

Jason Hsu: I have finally successfully deployed simple apps on Heroku in following the tutorial at Chapter 1: From zero to deploy | Ruby on Rails Tutorial | Learn Enough to Be Dangerous . Are there other free sites like Heroku? I want to deploy on other sites as well, so that I caern see what the differences are from one site to another. Congrats on getting your Rails app deployed on Heroku! There are several alternatives you can try, although the free tiers and features can change over time.…

What is the best way to integrate flight booking APIs into a Rails travel app?

How can I allow users from different countries to see and pay for travel bookings in their own currency? From your PSP of choice (Stripe / Braintree / 3C / etc) then you can enable Dynamic Currency Conversion (DCC) which allows for your customer to choose either your base currency (perhaps GBP if you’re located in England) or their currency of choice. Usually (but not always) the customer will get a more favorable rate of conversion by going through their financial institution as compared with…