# Form\_for and saving models

**URL:** <https://www.ruby-forum.com/t/form-for-and-saving-models/171327>\
**Category:** Rails\
**Created:** [June 30, 2009, 7:07pm UTC](https://www.ruby-forum.com/t/form-for-and-saving-models/171327 "2009-06-30T19:07:01Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Jesterman81](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e47c2d/32.png) [@Jesterman81](https://www.ruby-forum.com/u/Jesterman81)\
**Post date:** [June 30, 2009, 7:07pm UTC](https://www.ruby-forum.com/t/form-for-and-saving-models/171327/1 "2009-06-30T19:07:01Z")

</div>

Greetings Ladies and Gents,

I am learning rails and am wondering about a best practice? Currently  
I am trying to save specific tasks for a project. So tasks has a  
belongs\_to :project and project does has\_many :tasks. Well when  
creating a new task I need to store to project\_id in the tasks table.

Currently I can set the @tasks.project\_id = @projects.id in the  
TasksController create method or I can set the @task.project\_id =  
@project.id in the TasksController new method and set a hidden\_field  
in the form\_for for project\_id for task.

Both ways seem unsexy, but its the best way I found. Is there a  
better way? This is a nested resource also.

Current code:

\<% form\_for [:project, @task] do |form| -%\>

```
<fieldset>
    <legend>Project Info</legend>
    <% fields_for :project do |p| %>
        <%= p.text_field :name, :disabled => :true %>
    <% end %>
</fieldset>

<fieldset>
    <legend>Task</legend>
    <%= render :partial => 'form', :object => form %>
</fieldset>
<p>
    <%= submit_tag 'Create' %>
</p>

```

\<% end -%\>

Thanks.

---

<div class="post-metadata">

**Author:** ![Jesterman81](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e47c2d/32.png) [@Jesterman81](https://www.ruby-forum.com/u/Jesterman81)\
**Post date:** [June 30, 2009, 10:05pm UTC](https://www.ruby-forum.com/t/form-for-and-saving-models/171327/2 "2009-06-30T22:05:44Z")

</div>

On Jun 30, 2009, at 10:06 AM, Jesterman81 wrote:

> @project.id in the TasksController new method and set a hidden\_field  
> Project Info  
> \<%= submit\_tag ‘Create’ %\>
> 
> \<% end -%\>
> 
> Thanks.

Assuming you use the hidden field, then in create, you can do

@project = Project.find(params[:project]  
@project.tasks \<\< Task.create(params[:task])

I believe this works, but it’s air code. In any event, the spirit of  
it is to create the task scoped by the project it belongs to rather  
than manually setting the id.

Make sense?
