在rails 3中使用具有嵌套路由的表单时出现问题

时间:2011-03-29 16:25:34

标签: ruby-on-rails-3 form-for nested-routes

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

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

即路径应为 article / new / people / new

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

article.rb(model)

attr_accessor :new_person

articles_controller.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

form.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 提交&#34; sub&#34;将new_person字段添加到文章/ 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 form问题的解决方案。

非常感谢。

0 个答案:

没有答案