views:

140

answers:

2

Sorry for the semi-generic title, but I'm still pretty new at rails and couldn't think of a succinct way to put the question.

I have a basic habtm model setup: a Project has many Resources and a Resource can have many Projects. I have the database and models setup properly, and can do everything I need to via the console, but I'm having trouble translating it all into the view.

On the show view for the Project, I want to be able to create a Resource and automatically assign it to the current Project. Here's my basic html:

<p>
  <b>Name:</b>
  <%=h @project.name %>
</p>

<h2>Equipment</h2>
<ul>
  <% @project.resources.each do |r| %>
    <li><%=h r.name %></li>
  <% end %>
</ul>
<h2>Add A Resource</h2>
<% form_for(@project) do |f| %>
  <%= f.error_messages %>

  <p>
    Resource Name:<br />
    <%= f.text_field :resources %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

Obviously, that form won't work, but I'm at a loss for what to do next. I've searched around for various examples, but haven't found one for what I'm trying to do here.

One thing I've thought of was to change the form to be form_for(Resource.new) and include a hidden input of the @project.id. And then when the resource_controller handles the form, check for that id and go from there. That seems like an ugly kludge though.

+1  A: 

I believe you should use something like

<% form_for(@project) do |f| %>
   <%= f.error_messages %>
   <% f.fields_for :resources do |resource_fields| %>
      <%= resource_fields.text_field :name %>          
   <% end %>
<% end %>

but I'm really not sure! ;]

j.
This helped, I'm getting closer! In my project_controller, this parameter is passed: 'project"=>{"resources"=>{"name"=>"New Resource"}}' How can I build a new Resource object from that? I tried "@new_resource = @project.resources.build(params[:resources])" but that didn't work. Thanks again.
swilliams
I believe the right is `@project.resources.build(params[:project][:resources])`
j.
Ha, yeah I just figured that out myself too. Thanks.
swilliams
+1  A: 

If you are using Rails 2.3 or newer, you could try using accepts_nested_attributes_for to have your Project automatically create the Resource when it receives the attributes for a new resource. It also has the advantage of not needing anything special added to your controller.

Ryan Daigle wrote an excellent intro to accepts_nested_attributes_for, and there is also a nice railscast (#196) as well.

I have not tried it with a HABTM relationship though, but I imagine it would work similarly to the has_many example.

James