select field, text field and foreign key
new.html.erb
is the format of the new
action of the Team
controller.
- The list of the people is extracted from the People
model.
def new
@team = Team.new
@people = People.all
end
I created an attribute in the Team
model to store the new_person
text field :
class Team < ActiveRecord::Base
attr_accessor :new_person
...
end
Finally, here's an extract of my view :
<%= f.select :person_id, @people.map { |p| [p.name, p.id] } %>
<%= f.text_field :new_person %>
Obviously, I would like to save the new person in the table Person
before saving the data from the form. As usual, the id are saved instead of the names
At this point, I've got two issues :
1/ The params array has the keynew_person
what doesn't have the table. 开发者_开发知识库So it is not possible to use the Team.new(params[:team])
method. Does exist an easy solution to avoid this problem ?
2/ As I need the person_id, how can I get it when the name comes from the new_person
field? In using the before_filter
method ?
Thanks a lot,
Camille.1) You should consider using fields_for in your view within your form_for block. This will allow you to specify that the fields within the fields_for block are attributes of a different model, will generate the appropriately named input fields, and allow you to use params[:team] in your controller. See the FormHelper documentation for more on this.
2) While you could do something in your controller to first check for a value in the new_person field, create the record, update the contents of params[:team] with the value of the newly created person and create the team, this feels a bit like a hack to me. Another possible solution which may be less fragile would be to use some JavaScript on the page that would render some kind of modal dialog for the user to create the new person, submit the new person to the person#create controller method, then refresh your drop down. It would probably not be terribly difficult to do this using a jQuery UI modal form (very good example at that link to do what you need) with Rails remote form and unobtrusive JavaScript.
This is probably a more difficult solution to your second question than you are hoping for, but probably more useful in the long run.
精彩评论