views:

194

answers:

2

I'm very new with rails and I've been building a CMS application backend.

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

+3  A: 

First off I don't think you need second model for this. You could simply define method extended? for Page model which returns true if all (or any) of the attributes of extended page model are present.

Also you may want to look into fields_for form helper method. 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 %>
Eimantas
+1  A: 

Yes, it is. 'Nested forms' and 'fields_for' is your answer.

<% 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])