I’m looking for the functionality described here:
My application is very simple.
I have a note model and a project model. A note belongs to a project
and a project has many notes. When I create a note I would like the
option to select an existing project or to create a new one. What’s not
explained in the Railscast (I’m unable to watch it now to verify but
when I did watch it I didn’t hear an explanation) is how to handle the
form in your controller.
Some code:
Note model:
Associations
belongs_to :project
attr_accessor :new_project_name
before_save :create_project_from_name
def create_project_from_name
create_project(:name => new_project_name) unless
new_project_name.blank?
end
View:
<% form_for :note, :url => { :action => :add } do |form| %>
New Status Item:
<%= form.text_area:body, :cols => ‘20’, :rows => ‘5’ %>
Select Project:
<%=
form.collection_select :project_id, Project.find(:all, :order => ‘name
ASC’), :id, :name, :prompt => “Select a Project” %>
or create one:
<%= form.text_field :new_project_name %>
<%= submit_tag “Add Status Note” %>
<%end%>
Controller:
def add
# Create a Note object with data from the submitted form
@body = params[:note][:body]
@user_id = session[:perm]
@project_id = # Should be the ID of the selected project or the ID
of the newly created
@note = Note.create(:body => @body,
:project_id => @project_id,
:user_id => @user_id,
:project_id => @project_id)
end
As you can see I don’t have any code to determine how to determine the
correct ID of the project when I write the note to the database. My add
action could also be built incorrectly with the methodology involved, it
works otherwise but I don’t know if it’s the best practice for handling
form data… Any comments on my code would welcomed as well.
Thanks