无法在嵌套路由中将 project_id 设置到数据库中

not able to set project_id into databse in nested route

我创建了一个项目脚手架,其中包含一对多责任关联。我能够呈现责任形式,但我无法将 project_id 设置为责任 table。我创建了一对多关联。

这是我的代码-

routes.rb

  resources :projects do
    resources :responsibilities
  end

责任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

循序渐进

新应用

rails new bookstore

添加脚手架作者

rails g scaffold author name

添加脚手架书

rails g scaffold book name author:references

正在更新路线

来自

resources :books
resources :authors

resources :authors  do
    resources :books
end

让我们在app/views/authors/show.html.erb中显示link到新书,添加

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

在创建第一个作者并访问 http://localhost:3000/authors/1/books/new 后,我们有一个您遇到的错误:Books 中的 NoMethodError#new

undefined method `books_path'

要修复,首先在 BooksController 中添加

before_action :set_author, only: [:new]

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

并且在app/views/books/_form.html.erb

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

再次光顾http://localhost:3000/authors/1/books/new

书中的名字错误#new

undefined local variable or method `books_path'

修复 app/views/books/new.html.erb

改变

<%= link_to 'Back', books_path %>

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

现在我们可以渲染 http://localhost:3000/authors/1/books/new

我认为这里有您需要的一切