简体   繁体   English

在Rails中组合两个模型以形成一个表单

[英]Combining Two Models in Rails for a Form

I'm very new with rails and I've been building a CMS application backend. 我对Rails非常陌生,而且我一直在构建CMS应用程序后端。

All is going well, but I would like to know if this is possible? 一切进展顺利,但我想知道这是否可能吗?

Basically I have two models: 基本上我有两个模型:

@page { id, name, number }

@extended_page { id, page_id, description, image }

The idea is that there are bunch of pages but NOT ALL pages have extended_content. 这个想法是有很多页面,但并非所有页面都具有extended_content。 In the event that there is a page with extended content then I want to be able to have a form that allows for editing both of them. 如果存在带有扩展内容的页面,那么我希望能够拥有一个允许对它们进行编辑的表单。

In the controller: 在控制器中:

@page = Page.find(params[:id])
@extended= Extended.find(:first, :conditions => ["page_id =
?",@page.id])
@combined = ... #merge the two somehow

So in the view: 所以在视图中:

<%- form_for @combined do |f| %>

<%= f.label :name %>
<%= f.text_field :name %>

...

<%= f.label :description %>
<%= f.text_field :description %>

<%- end >

This way in the controller, there only has to be one model that will be updated (which will update to both). 通过这种方式,在控制器中,仅需更新一个模型(即可同时更新两个模型)。

Is this possible? 这可能吗?

First off I don't think you need second model for this. 首先,我认为您不需要第二个模型。 You could simply define method extended? 您可以简单地定义extended?方法extended? for Page model which returns true if all (or any) of the attributes of extended page model are present. for Page model,如果存在扩展页面模型的所有(或任何)属性,则返回true

Also you may want to look into fields_for form helper method. 另外,您可能需要查看fields_for表单帮助器方法。 Something like this should go into your view: 这样的事情应该进入您的视野:

<%- form_for @combined do |f| %>

<%= f.label :name %>
<%= f.text_field :name %>

<%- f.fields_for(:extended_page) do |ef| %>

  <%= ef.label :image %>
  <%= ef.file :image %>
  <!-- other extended page form fields -->

<%- end %>

<!-- Other page form fields -->
<%- end %>

Yes, it is. 是的。 'Nested forms' and 'fields_for' is your answer. “嵌套表格”和“ fields_for”是您的答案。

<% form_for @combined do |form| %>
  <% form.fields_for :page do |nested_form| %>
    <%= nested_form.label :name %>
    <%= nested_form.text_field :name %>
   <% end %>
  <% form.fields_for :extended_page do |nested_form| %>
    <%= nested_form.label :desciption %>
    <%= nested_form.text_field :description %>
   <% end %>
 <% end %>

The post params will look like 发布参数看起来像

{ "combined" => 
     "page" => {"name" => "the name"},
     "extended_page" => {"description" => "the description"}
}

so you should be able to create a page and extended page by something like 因此您应该可以通过类似以下方式创建页面和扩展页面

page = Page.new(params[:combined][:page])
extended_page = ExtendedPage.new(params[:combined][:extended_page])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM