# Saving foreign key id's using form\_for?

**URL:** <https://www.ruby-forum.com/t/saving-foreign-key-ids-using-form-for/171293>\
**Category:** Rails\
**Created:** [June 30, 2009, 4:54am UTC](https://www.ruby-forum.com/t/saving-foreign-key-ids-using-form-for/171293 "2009-06-30T04:54:30Z")\
**Posts on this page:** 1\
**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, 4:54am UTC](https://www.ruby-forum.com/t/saving-foreign-key-ids-using-form-for/171293/1 "2009-06-30T04:54:30Z")

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