/r/rails

Photograph via snooOG

A subreddit for discussion and news about Ruby on Rails

Looking for help?

Please make sure you've tried searching Google and StackOverflow.

If you still need help, please follow the rules in How do I ask for help?


Learning ruby/rails?

Scroll down a bit more for great learning resources.


Looking for a gem?

Please check out the links in the wiki before posting.

A subreddit for discussion and news about Ruby on Rails development

Posts about the Ruby programming language are encouraged to be posted in the /r/ruby subreddit.

Please message the mods if you would like to suggest changes to the sidebar.

Learning Ruby?

  • TryRuby in your browser
  • Try RubyKoans to learn more about syntax, structure, and common functions and libraries
  • Hackety Hack is a shoes app for playing around with ruby

Learning Rails?

Tools

Docs

  • APIdock: Rich and usable interface for searching, perusing and improving the documentation
  • Rails API: Searchable docs built with the sdoc gem.
  • rdoc: YARD Documentation Server
  • Ruby Doc: Complete and accurate documentation for the Ruby programming language
  • RelishApp Browsable Cucumber Features

Community

Rails jobs

Looking for work, or need to hire Rails developers?

Try /r/railsjobs, /r/forhire, or the following job sites:

/r/rails

65,488 Subscribers

3

Newbie question about tags

Hi folks I'm learning rails building a small guest-book app. I wanted to add tags (as everyone else suggested) but the grm thst they suggest acts-as-taggable-on won't work for me somehow.I foundthis one https://rubygems.org/gems/no_fly_list but I'm not sure tbh . Any insight?

9 Comments
2024/12/21
13:36 UTC

7

xray-rails (but in very simple)

I really liked xray-rails back in the days but it's a bit dated and as it turns out somewhat unnecessarily bloated...?

Inspired by it, I made a crude but lightweight version. Not sure how you only gonna add the JS in development but that's up to you (and figuring this out is also the biggest issue with xray-rails)

Screenshot: https://i.imgur.com/ei1pPHU.png
Source: https://gist.github.com/2called-chaos/aea0ca4fec45d185ee2016b024ba22e3


  1. enable in your config/environment/development.rb

     config.action_view.annotate_rendered_view_with_filenames = true
  2. Add to your routes.rb

     post "__xray/open", to: ->(env) {
       editor = ENV["GEM_EDITOR"] || ENV["VISUAL"] || ENV["EDITOR"] || "/usr/local/bin/subl"
       params = JSON.parse(Rack::Request.new(env).body.read)
       path = Rails.root.join(params["path"].to_s)
       `#{editor} #{path.to_s.shellescape}` if path.exist?
       [200, { "Content-Type" => "text/plain" }, [""]]
     } if Rails.env.development?
  3. Include and use JS somewhere

     import { registerXrayShortcut } from "./xray_rails"
     // CommandOrControl + Shift + x
     registerXrayShortcut((ev, mac) => (mac && ev.metaKey || !mac && ev.ctrlKey) && ev.shiftKey && ev.code == "KeyX")

Note: the editor should NOT be a blocking one (i.e. not "subl -w")

0 Comments
2024/12/21
05:32 UTC

0

Rails 8 x Heroku’s Future

I posted recently discussing a go-to one-man stack for Rails and had taken Heroku’s place as my de-facto PaaS a given. After looking further into Rails 8 however, I’m growing concerned that Heroku and Rails are diverging. Rails now ships with kamal by default, and Heroku’s default DB setup doesn’t lend itself well to Rails 8’s new 4 database setup recommendation. On top of that, Heroku’s Rails 8 tutorial was somewhat weak and vague and not confidence inspiring.

I’d like to hear anyone’s experience/opinion using Heroku and Rails 8 and their take on the general relationship between the two going forward. Really hoping the answer is not what I think it is!

12 Comments
2024/12/21
04:25 UTC

10

Seeking advice on leveling up on rails

Hello wonderfull people of rails. I have been learning rails for few months now. I started with odin project rails course which covers all basic aspects active records, mailer, controllers, routes, bit of active jobs etc. I have also gone through the rubyonrails guides page. This has enabled me to build basic crud apps(2k loc) with authentication and some reactivity.

Now, I am looking to get to the next level and learn some advanced concepts. I looked at gorails which is very nice, but also very overwhelming. A friend recommended learning about polymorphism, caching, eager loading etc. Those are all very practical and would love to compile a list of these practical intermediate and advanced topics.

Can someone help me with a learning path/advice that I can follow ?

14 Comments
2024/12/21
02:35 UTC

3

Has anyone gotten Doorkeeper working with Rails 8 Authentication?

1 Comment
2024/12/20
21:33 UTC

5

Need advice from folks skilled in metaprogramming

Hi railroad workers!

It looks like I'm trying to do something weird but I keep getting back to this idea over and over.

My idea: I want to be able to extend my AR-based model instances with extra functionality by mixing modules into their singleton classes.

Here is what I currently have:

class Pet < ApplicationRecord
  #   some stuff
end

module ShouldHaveFunnyName
  def self.extended(base)
    base.singleton_class.class_eval do
      validates :name, inclusion: %w[Sniffles Furdinand Subwoofer]
    end
  end
end

dog1 = Pet.new(name: 'Buddy')
dog1.extend(ShouldHaveFunnyName)
p dog1.valid? # false
dog1.name = "Subwoofer"
p dog1.valid? # true
dog2 = Pet.new(name: 'Buddy')
p dog2.valid? # true

In the example above I "enhance" one of the Pet instances with an additional validation. And it kinda works as expected.

Why?

My models tend to grow over time and something that I realized is that a lot of that code is only needed in a few very specific scenarios. My thinking is to extract the code that is rarely used into these "enhancers" and explicitly use them whenever I need.

Of course I know about ActiveSupport::Concern but it's not what I have in mind. I don't want to even have this logic in my models unless I explicitly use it.

Now, ChatGPT is not happy with me about this. It says that "I'm pushing Rails API beyond its design" (it's specifically not happy about using validations like this b/c they are intended to be used on the class level and are probably not tested on the singleton class level.

I'm also probably missing all possible problems of combining multiple "enhancers" and getting ambiguous behavior or getting different behavior by simply changing their order.

Anyway, what are your thoughts on this?

37 Comments
2024/12/20
18:30 UTC

11

Why APICraft Rails was created?

Recently as part of an API Design first workflow we were looking at tools to implement this. What we ended up observing was that the ecosystem to get this working is quite fragmented and it's understandable why. Most of the community is into rapid prototyping.

However, we also discovered that there are a lot of organizations that use Rails as their primary monolith serving APIs to enterprise clients or internal FE clients and other tools. Given this use case, we built some internal tooling that helped us develop faster. It enabled us to have working APIs in seconds, with no implementations. Our clients could start using it from Day 0 just based off the contracts. This approach enabled us to parallelize our development workflows, allowing front-end teams or other consumers to proceed independently of API implementation timelines.

The results were transformative for our workflow, and we realized this tool could benefit others as well. To share this capability with the community, we’ve packaged it as a Rails gem. While there’s still room for improvement, the gem already delivers significant value and helps teams embrace an API Design-first approach with ease.

We’re excited to see how others use it and contribute to its growth!

https://github.com/apicraft-dev/apicraft-rails

4 Comments
2024/12/20
11:49 UTC

2

Check is nested model changed after save

Is there any way in rails to check in model with callback after save, is model object or some of his nested objects in db realy changed?

2 Comments
2024/12/20
11:02 UTC

7

Update the Rails version

Greetings!

Here’s the situation: I need to update the Ruby and Rails versions in a project (Ruby 2.6 and Rails 5.2). What do you suggest? Should I update version by version? create a new app? And if that's the case, what should I do with the migrations?

9 Comments
2024/12/20
00:20 UTC

7

Struggling with dynamic forms with Stimulus

I'm new to the Rails ecosystem and still adjusting to its way of doing things. My background is mostly in building frontends with SPA frameworks like React, so some concepts here feel very different to me.

As a learning project, I'm building a Rails app for tracking weightlifting workouts. My goal is to allow users to start with a blank workout form and dynamically add exercises to the workout. For each exercise, they can also add sets as they progress through the workout.

I’m struggling to implement this dynamic form in Rails, especially since the number of exercises and sets is unknown when the form loads. I’ve been exploring Stimulus for handling the interactivity, but my implementation is becoming messy and verbose. It feels like I might be missing something fundamental, as Stimulus seems to focus on "sprinkling" JavaScript rather than handling complex logic.

Here are my main questions:

  1. Am I going against the "Rails way" by trying to use a dynamic form like this?
  2. Is Stimulus the right tool for this? If so, what’s the best approach to keep the Stimulus controllers manageable when adding sub-forms dynamically?
4 Comments
2024/12/19
22:14 UTC

12

Video for RubyConf 2024 Workshop: How To Build Basic Desktop Applications in Ruby (includes mentions of Rails)

I am sharing this RubyConf 2024 workshop video in the Rails group because it mentions Rails on several occasions, it helps devs build Rails productivity GUI tools as Ruby gems (e.g. the rails-gui gem offers a user-friendly fast GUI for rails routes) with the Fukuoka Ruby 2022 Award Winning Glimmer DSL for LibUI (Prerequisite-Free Ruby Desktop Development Cross-Platform Native GUI Library), it improves Rails developer skills in OOP, Software Architecture, Software Design, MVC, and MVP, and it concludes by mentioning the new Glimmer DSL for Web, which provides devs with all the awesome features of Glimmer desktop gems, but in the Frontend of Rails Web Applications. 🤯

https://andymaleh.blogspot.com/2024/12/video-for-rubyconf-2024-workshop-how-to.html

0 Comments
2024/12/19
21:48 UTC

26

Launched a lightweight deprecation monitoring tool

Ruby gems use deprecation warnings to let users know about upcoming breaking changes that will affect their codebase. Larger projects like Rails rely heavily on these warnings for communication — the Rails upgrade guide, for example, won’t even mention minor breaking changes as long as there’s a deprecation warning in place. Missing any of these warnings during an upgrade can lead to an unexpected failure in production.

Our tool monitors for deprecation warnings at runtime, helping you catch breaking changes that aren’t covered by your test suite. You can install our gem in your staging, QA, and production environments to track warnings before you merge a breaking change in an upgrade. Under the hood it works similarly to an error tracking system like Rollbar or Sentry but for deprecations instead.

You can try it out (for free) by following the instructions in the docs. Would love any feedback.

0 Comments
2024/12/19
18:26 UTC

6

Easy way to cache ActiveRecord models in memory?

Suppose User belongs_to Doctor, and user #1 and user #2 both belong to doctor #4. I'd like to be able to:

user = User.find(1)
user.doctor # <- loads doctor id: 4 from db

user = User.find(2)
user.doctor # <- would load this doctor from memory

Has anyone done something like this before? Is there a Rails way or some built-in functionality that might help?

Without going too deep into details, there's some complex logic that makes running .includes(:doctor) each time a bit challenging.

Thank you for any help!

5 Comments
2024/12/19
16:52 UTC

5

Payment integration through Rails generators?

Hey everyone, I have been looking into payment integration with Rails (specifically stripe subscriptions and checkouts) and I was wondering if there is a gem that streamlines payment integrations through rails generators. I have picked rails again in years so I am looking for something easy to setup and well documentation. Thanks!

6 Comments
2024/12/19
14:06 UTC

15

Anyone have any part time Rails contract work leads?

Hey folks, I am a US based Rails dev with 6 years of full time experience. I am employed full time but looking to supplement with about 15 hours per week of rails contract work.

My expertise is mostly backend but I can hold my own with UI work as well. I am happy to provide my resume via DM.

15 Comments
2024/12/19
05:00 UTC

6

Changes in stimulus controller are not applied by default

Hi guys, I am with a Rails 7 app with stimulus, and I have a problem that didn't have before.

Changes in stimulus controller's code, are not being saved by default.

I have to manually assets:clobber && assets:precompile and is driving me nuts.

Can someone point me to a reason for this and a fix? Thanks

7 Comments
2024/12/18
14:17 UTC

74

Why do developers get stuck at mid-level? (and an idea to fix it)

Hey folks! Since 2008, I've worked as a Ruby on Rails developer and have a passion for understanding how developers learn and develop their skills. Over the years, I've mentored tons of devs and noticed a pattern: once developers hit mid-level (around 2–4 years of experience), they often get stuck.

You're good at your job, but it's tricky to figure out how to grow further. The problems you're solving are getting more complex, but finding effective ways to level up feels harder than it should.

Sure, there are many resources (videos, books, courses, blogs, conferences, etc.), but they're scattered and disconnected. It's like trying to assemble a puzzle when the pieces are spread across different rooms and the picture isn't even on the box.

So, I'm testing a new learning format called Skill Sprints:

  • Two weeks of live workshops and QnA sessions led by expert devs
  • Focused, short-term deep dives into advanced topics like performance optimization, architecture, system design, high load, etc.
  • Hands-on skills you can apply to your projects immediately
  • Small groups for real collaboration and feedback

I tested this format with groups of up to 20 attendants, and the results were promising. In just two weeks, participants gained new skills and the confidence to tackle more complex challenges.

I'm considering launching this format for a wider audience and would love your thoughts.

Sure, one Skill Sprint won't make anyone a senior developer overnight, but it will give them a clear, solid piece of the puzzle on which to build. I plan to run these regularly to help participants develop a well-rounded senior-level skill set (technical mastery).

What do you think about this idea? Does it resonate with you? What topics would you want to see covered? Drop your thoughts in the comments—I'd love to hear from you!

UPD: Thanks for all the insightful comments! Many of you highlighted the importance of soft skills for reaching the senior level, and I completely agree. For now, Skill Sprints are focused on technical mastery, but I’d love to explore ways to address soft skills in the future.

UPD 2: The goal of this post was just to discuss the concept, but since there’s interest and some of you want to sign up, I’ve created a simple waitlist form. No spam, just updates when the first Skill Sprint launches.
Join the waitlist here: https://forms.gle/d2pJwY73HVRCTohx5

42 Comments
2024/12/18
14:06 UTC

1

Configuring React with Rails

I'm trying to build an app like Shareit(Photo, music & file sharing app) using RoR, with React as the front end.

How to integrate React with rails?

Should I use Esbuild or importmap or rollup or vite or interia.js or seperate react spa with rails api or any other way?

3 Comments
2024/12/18
12:32 UTC

3

omniauth-google-oauth2 auth issue

I'm using omniauth-google-oauth2 for rails react application. Signup and Login feature working in my local machine without any errors. but when someone pull my frontend and backend from my brach and try to run it on there , it gives This localhost page could not be found. The web page at http://localhost:4000/auth/google_oauth2, HTTP ERROR 404.

For this development I used personal email to setup Google Cloud Platform. I gave them CLIENT ID and CLIENT SECRECT keys but still getting above issue. Do they need to create Google Could Platform account and replace my keys ?

Can someone please help me.

0 Comments
2024/12/18
08:23 UTC

5

Active Module: Let's turn modules and classes into first-class active record values!

I've just published this little gem and would like to have some feedback to improve. Is this something you would use? If not, why?

https://github.com/pedrorolo/active_module

19 Comments
2024/12/18
07:52 UTC

53

In this fast-paced world of Building and Shiping fast Rails Continues to Be a Great Choice for Developers, and I'm Happy I Took the Time to Learn It!

I simply wanted to bring up a briefly note on RoR, which I believe is incredibly underestimated in the area of rapid building and deployment, particularly if you're a solo founder trying to create and ship your product rapidly Rails is definitely the way to go!

With all the new frameworks popping up, it’s easy to forget how powerful Rails is, which has been around for quite some time and the ruby way of doing things means you can focus on what really matters—building your app—without getting lost in endless setup and boilerplate.

Oh, and with Hotwire and Kamal coming into play, I can’t help but feel that RoR is the best bet for option for quickly building and shipping quality apps. I think It’s time to admit that the old school is making a comeback and was once old is now new again!

7 Comments
2024/12/17
17:31 UTC

2

If you invert a from and to of a spot we get more than 24h of work. HELP PLEASE!

So the code is as follow belows. In the front the client chooses a set of work hour from a certain hour to another. This works okay! The problem is that the client instead of creating a new spot or something sometimes just inverts the from and to, this causes the work to be more then 24h.

For example, lets say that one schedule is from 7Pm to 7AM Saturday ending in Sunday, if the client edits this same spot to 7AM to 7PM, instead of the 12h work journey happening only on Saturday, we have the 7AM Saturday to 7PM Sunday. This makes the work journey more then 24h.

the code on back

to = @spot[:to]
    from = @spot[:from]

    to = Time.parse(spot_params[:to]) if spot_params[:to]
    from = Time.parse(spot_params[:from]) if spot_params[:from]

    to += 1.day if to <= from

the code on front:

const newFrom = new Date(`${format(new Date(s.from), 'yyyy/M/d')} ${from}`);

    const newTime = new Date(`${format(new Date(s.from), 'yyyy/M/d')} ${to}`);

    if (newTime < newFrom) newTime.setDate(newTime.getDate() + 1);

The client cannot change the dates by themselves after creating the spot, only edit the hours, so the work to maintain the same day after inverting it must be of the code.
Does any of you know how to help?

10 Comments
2024/12/17
15:48 UTC

2

pg_search and how to order/ranked with good performance

I am using the pg_serach gem on my website. Link

I want to order the results by ratings_abs

I was checking that I have two solutions:

to edit the controller with something like this

class ItemsController < ApplicationController
  def index
    if params[:query].present?
      @items = Item.search_all(params[:query]).order(ratings_abs: :desc)
    else
      @items = Item.all.order(ratings_abs: :desc)
    end
  end
end

or to use ranked_by (teorically it is not exactly the same, I know, but the result, less or more, is the same), and to edit my item.rb model like this

pg_search_scope :search_all,
  against: [ [:title, "A"],
             [:author, "B"],
             [:description, "C"]
           ],           using: { tsearch: { prefix: true } },
           ranked_by: ":tsearch + (0.1 * ratings_abs)"

now my question is... what about the performance? Why?

I have the same results but I don't undestand which one has better performance.

0 Comments
2024/12/17
08:11 UTC

Back To Top