Skip to main content

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

Rails • Asked by Ivan Ray M. Buglosa

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?

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.