Rails 7.1: A New Way to Link to Models

Rails 7.1 introduces a new feature that makes it easier to link to models in your views. With this new feature, you can use the link_to helper to generate a link to a model without having to explicitly specify the text of the link. This can make your code more concise and easier to read.

To use this feature, you need to override the to_s method in your model class to return the text you want to display for the link. For example, in the Profile model, you could override the to_s method like this:

1
2
3
4
5
class Profile < ApplicationRecord
  def to_s
    name
  end
end

In previous versions of Rails. you had to explicitly specify the text of the link when using the link_to helper. This could make your code more verbose and difficult to read. For example, to generate a link to a profile, you would have to write the following code:

1
link_to @profile.name, @profile

In Rails 7.1, you can then use the link_to helper to generate a link to a profile like this:

1
link_to @profile

This will generate a link with the text of the profile’s name.

Benefits of the New Feature

The new link_to feature in Rails 7.1 offers several benefits, including:

The new link_to feature in Rails 7.1 is a great addition to the framework. It is a simple but powerful feature that can make your code more concise, easier to maintain, and more accessible. I encourage you to try it out in your next Rails project.