All threads / How to save a record in a nested form from a namespaced resource?
Ask A Question


You’re not receiving notifications from this thread.

How to save a record in a nested form from a namespaced resource?

Ivan Ray M. Buglosa asked in Rails

I have a nested form from a namespaced resource...


class Word < ApplicationRecord
  belongs_to :category

  has_many :choices
  accepts_nested_attributes_for :choices

  validates :content,presence: true, length: { maximum: 20 }


class Choice < ApplicationRecord
  belongs_to :word

  validates :content, presence: true, length: { maximum: 20 }
  validates :word_id, presence: true
  validates :correct, presence: true


def new
    @word =  
    3.times {

    def word_params
    params.require(:word).permit(:content, choices_attributes: [:id, :content, :correct])

Word new.html.erb

<div class="container mt-4">
            <div class="row">
                <div class="col-lg-6 offset-lg-3">
                    <%= form_for([:admin, @word.category]) do |f| %>
                        <%= render 'shared/error_messages', object: f.object %>
                        <div class="form-group">
                            <%= label_tag :content, "Word"%>
                            <%= f.text_field :content, class: 'form-control', placeholder: 'Word' %>

                        <%= label_tag :content, "Choices" %>
                        <small class="text-muted">(Please check the correct choice)</small>

                        <%= f.fields_for :choices do |choice| %>
                            <div class="form-group">
                                <div class="form-row">
                                    <div class="col-lg-9">
                                        <%= choice.text_field :content, class: 'form-control', placeholder: 'Choices' %>
                                    <div class="col-lg-3">
                                        <%= choice.label :correct %>
                                        <%= choice.check_box :correct, type: 'checkbox' %>
                        <% end %>
                        <div class="form-group">
                            <%= f.submit "Save", class: 'btn btn-primary btn-block' %>
                    <% end %>

I forgot to add the routes.

namespace :admin do
resources :categories do
resources :words

From a quick glance all looks good. Any error? Does the log give you anything?

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 69,840+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.