Rails has-and-belongs-to-many form question
Posted
by swilliams
on Stack Overflow
See other posts from Stack Overflow
or by swilliams
Published on 2010-06-14T17:25:14Z
Indexed on
2010/06/14
20:42 UTC
Read the original article
Hit count: 269
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.
© Stack Overflow or respective owner