Search code examples
ruby-on-railsruby-on-rails-5

not able to set project_id into databse in nested route


i have created a project scaffold with one to many association with responsibility. i am able to render responsibility form but i am not able to set project_id into responsibility table. i have created one to many association.

here are my code-

routes.rb

  resources :projects do
    resources :responsibilities
  end

responsibility form.html.erb

<%= form_with(model: responsibility, url: [@project, responsibility], local: true) do |form| %>
  <% if responsibility.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(responsibility.errors.count, "error") %> prohibited this responsibility from being saved:</h2>

      <ul>
      <% responsibility.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :responsibility_matrix %>
    <%= form.text_field :responsibility_matrix %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

responsibilities_controller.rb

  def new
    @project = Project.find(params[:project_id])
    @responsibility = Responsibility.new
  end

Solution

  • Step by step

    New app

    rails new bookstore
    

    Add scaffold author

    rails g scaffold author name
    

    Add scaffold book

    rails g scaffold book name author:references
    

    Updating routes

    From

    resources :books
    resources :authors
    

    To

    resources :authors  do
        resources :books
    end
    

    Let's show link to new book in app/views/authors/show.html.erb, add

    <%= link_to 'New book', new_author_book_path(@author) %> |
    

    After create a first Author, and visiting http://localhost:3000/authors/1/books/new we have a erro that you have: NoMethodError in Books#new

    undefined method `books_path'
    

    To fix, first in BooksController add

    before_action :set_author, only: [:new]
    
    private
    def set_author
      @author = Author.find(params[:author_id])
    end
    

    And in app/views/books/_form.html.erb

    <%= form_with(model: book, url:[@author, book], local: true) do |form| %>
    

    Visiting again http://localhost:3000/authors/1/books/new

    NameError in Books#new

    undefined local variable or method `books_path'
    

    Fix in app/views/books/new.html.erb

    Change

    <%= link_to 'Back', books_path %>
    

    to

    <%= link_to 'Back', author_books_path(@author) %>
    

    Now we can render http://localhost:3000/authors/1/books/new

    I think that here you got all you need