In Rails, modeling indirect associations is easy, but editing them through forms can be tricky. Let’s walk through two clean ways to let users select a Category (grandparent) for a Url (child), where the association runs through an intermediate Domain (parent).
We’re working with the following model setup:
class Category < ApplicationRecord has_many :domains end class Domain < ApplicationRecord belongs_to :category has_many :urls end class Url < ApplicationRecord belongs_to :domain has_one :category, through: :domain end
In the Url form, allow the user to select a Category, and update the associated Domain’s category_id accordingly.
class Url < ApplicationRecord belongs_to :domain has_one :category, through: :domain delegate :category_id, :category_id=, to: :domain, allow_nil: true end
def new @url = Url.new @url.build_domain unless @url.domain end
<%= simple_form_for @url do |f| %> <%= f.input :name %> <%= f.input :category_id, collection: Category.all, label: "Category" %> <%= f.button :submit %> <% end %>
params.require(:url).permit(:name, :category_id)
class Url < ApplicationRecord belongs_to :domain accepts_nested_attributes_for :domain end
<%= simple_form_for @url do |f| %>
<%= f.input :name %>
<%= f.simple_fields_for :domain do |df| %>
<%= df.input :category_id, collection: Category.all, label: "Category" %>
<% end %>
<%= f.button :submit %>
<% end %>
params.require(:url).permit(:name, domain_attributes: [:category_id])
def new @url = Url.new @url.build_domain end
Work with our skilled Ruby on Rails developers to accelerate your project and boost its performance.
Hire Ruby on Rails Developer