如何为两个相关模型制作一个表格?

时间:2016-04-13 04:09:31

标签: ruby-on-rails activerecord nested-forms form-for

我想为2个不同的模型编写数据,这些模型彼此相关:

class Post < ActiveRecord::Base
    has_many :roads
    accepts_nested_attributes_for :roads, :allow_destroy => true
end

class Road < ActiveRecord::Base
    belongs_to :post
end

当然de roads table有一个&#34; post_id列&#34;。我在后视图中的form_for看起来像这样

<%= form_for @post do |f| %>

  <div class="form-group">
    <%= f.label :Tu_Nombre %>
    <%= f.text_field :creador, class: "form-control" %>
  </div>


  <div class="form-group">
    <%= f.label :año %> (Cuando fue tu experiencia?)
    <%= f.text_field :año, class: "form-control" %>
  </div>

  <div class="form-group">
    <%= fields_for :roads do |r| %>
      <%= r.label :principio %> (desde?)
      <%= r.text_field :principio, class: "form-control" %>

      <%= r.label :final %> (hasta?)
      <%= r.text_field :final, class: "form-control" %>
    <% end %>
  </div>

  <div class="form-group">
    <%= f.label :historia %> (Cuentanos la historia de tu viaje!)
    <%= f.text_area :historia, class: "form-control", size: "50x15" %>
  </div>

  <div>
    <%= f.submit class: "btn btn-success" %>
  </div>

<% end %>

最后我的posts_controller创建方法

def create
@post = Post.new(post_params)

  if @post.save
    redirect_to @post, notice: 'Post was successfully created.' 
  else
    render :new 
  end
end

私人

 def post_params
   params.require(:post).permit(:historia, roads_attributes:  [:pricipio, :final, :post_id])
 end

提交帖子,如果我检查控制台,所有的帖子属性都已保存,但是道路的属性没有。我如何只为这两个模型使用一个表单两个make记录,并且post_id被注册,以便我可以关联表格?

非常感谢!!

3 个答案:

答案 0 :(得分:0)

请阅读Rails指南的表单助手章节中的Nested Forms。您可以使用fields_forroads构建嵌套属性表单,并允许嵌套属性(如示例)。以下是rails guide的示例,您可以尝试自己解决。

_form.html.erb

<%= form_for @person do |f| %>
  Addresses:
  <ul>
    <%= f.fields_for :addresses do |addresses_form| %>
      <li>
        <%= addresses_form.label :kind %>
        <%= addresses_form.text_field :kind %>

        <%= addresses_form.label :street %>
        <%= addresses_form.text_field :street %>
        ...
      </li>
    <% end %>
  </ul>
<% end %>

允许在people_controller.rb中嵌套属性

def person_params
  params.require(:person).permit(:name, addresses_attributes: [:id, :kind, :street])
end

答案 1 :(得分:0)

将您的fields_for附加到父表单构建器,如下所示:

<%= f.fields_for :roads do |r| %>

答案 2 :(得分:0)

更新您的posts_controller new方法以包含.build

def new
  @post = Post.new
  @post.roads.build
end