1

我有一个数据库结构,其中我的文章有很多人(通过连接,但工作正常)

我希望发生的是,当人们创建一篇文章时,他们可以同时创建新的人

即路径应该是article/new/people/new的形式

事实上,在不使用嵌套路由的情况下,我使用这种方法来管理它

article.rb(模型)

attr_accessor :new_person

文章控制器.rb

  def create
    @article = Article.new(params[:article])

    if params[:add_person]
      @person = Person.check_if_exists_or_create(@article.new_person["first_name"], @article.new_person["last_name"])
      if @person.save
        @article.people << @person
        @article.new_person = nil
      end
      render :action => "new" and return
    end
...

  end

表单.erb

<%= form_for @article  do |f| %>
...

      <%= fields_for :new_person do |p| %>

        <% if @person && @person.errors.any? %>
          <%= render :partial => "shared/error_messages", :object => @person %>
        <% end %>

        <div class="field">
          <%= p.label :first_name, "First Name" %>
          <%= p.text_field :first_name %>
        </div>

        <div class="field">
          <%= p.label :last_name, "Last Name" %>
          <%= p.text_field :last_name %>
        </div>

        <%= submit_tag "Add Person", :name => "add_person" %>

      <% end %>
...
  <p>
    <%= f.submit %>
  </p>


<% end %>

这在一定程度上可以正常工作,但现在表单变得越来越复杂,其他字段我认为我可以重构它以利用嵌套路由。

此外,它为创建控制器添加了很多逻辑——更进一步,我可能会考虑将这些操作设为 javascript,在这种情况下,我知道确定控制器按下的特定按钮会更加复杂。

由于这些原因,我认为嵌套路由方法可能更合适。

对于现有文章,它可以正常工作,例如/articles/1/people/new没有问题。

我知道嵌套表单是出于 html 验证等原因而禁止使用的,因此我尝试了多种 form_for 和 fields_for 组合来实现以下目标:

在文章/新页面上

将主表单提交给articles/new 将带有new_person 字段的“子”表单提交给articles/new/people/new

并尽可能轻松地通过 UJS 进行更改

我认为我得到的最温暖的是这个错误

No route matches {:controller=>"people", :article_id=>#<Article id: nil, title: nil, published_on: nil, created_at: nil, updated_at: nil, people_count: nil, organizations_count: nil>}

我猜这个问题是没有 article_id 可以将这个人与那个时候联系起来。

但事实上,我只对将那个人添加到数据库中然后创建与文章的关系商店感兴趣,然后在保存整篇文章时将其存储起来。

为长篇文章道歉,但想在我的问题中全面。

任何建议,包括更适合我的目标的替代方法,将不胜感激。我已经观看了与嵌套表单和嵌套路线相关的铁路广播,并阅读了我可以在网上找到的所有内容,但还没有找到 /model/new/submodel/new 表单问题的解决方案。

非常感谢。

4

0 回答 0