Ivan Ray M. Buglosa

Joined

60 Experience
0 Lessons Completed
0 Questions Solved

Activity

I forgot to add the routes.

namespace :admin do
resources :categories do
resources :words
end
end

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

Word.rb

class Word < ApplicationRecord
  belongs_to :category

  has_many :choices
  accepts_nested_attributes_for :choices

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

Choice.rb

class Choice < ApplicationRecord
  belongs_to :word

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

words_controller.rb

def new
    @word = Word.new  
    3.times {
      @word.choices.build
    } 
  end

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

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' %>
                        </div>

                        <%= 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>
                                    <div class="col-lg-3">
                                        <%= choice.label :correct %>
                                        <%= choice.check_box :correct, type: 'checkbox' %>
                                    </div>
                                </div>
                            </div>
                        <% end %>
                        <div class="form-group">
                            <%= f.submit "Save", class: 'btn btn-primary btn-block' %>
                        </div>
                    <% end %>
                </div>
            </div>
        </div>