5 items tagged “Rails”
2024
💡 TIL: pick is the single-value version of pluck in Rails #
Instead of doing
Messages.pluck(:user_id).firstyou can do
Messages.pick(:user_id)
💡 TIL: Rails ActiveRecord has a .sole method #
I just learned about `sole` and `find_sole_by`. They ensure that only a single record is returned and will raise if there is something other than one. It’s the equivalent of:
api_keys = user.api_keys.where(key: key) if api_keys.length == 1 api_key = api_keys.first elsif api_keys.length == 0 raise "No records found!" else raise "More than one matching record found!" end
🔗 Rails web-based database admin (#). A rails gem that gives you a web-based interface to your database.
💡 TIL: Rails migrations can include an up_only part #
When writing a migration in Rails and you need to do one thing which can’t be automatically reversed, I always convert a def change to up and down. It turns out you can slip in an up_only block:
class AddFieldsToUsers < ActiveRecord::Migration[7.1] def change add_column :users, :first_name, :string add_column :users, :last_name, :string up_only do User.delete_all end end endfrom RubyCademy
📝 Using Hotwire it was simple to build inline title editing #
After generating the Rails scaffolding for my “Conversation” model, it was just a few steps to do inline editing:
- Modify conversations/_conversation.html.erb to wrap it in a turbo-frame
- Modify conversations/_form.html.erb partial to wrap it in the same turbo-frame so that the form will replace the displayed title
- Add a tiny bit of stimulus to enable submit on enter/blur and to enable discard with Escape