RoR: multiple model handling in the same form?
I am beginning work on a record management application. system will allow users to manage records stored in the database, each record can have 1 or more object开发者_运维技巧s called categories and each category can have 1 or more objects called advantages. the way im thinking of doing it is i have 3 models: Record(has_many categories), Category(has a title field and belongs_to Record, has_many advantages), Advantage(has a title and description fields and belongs_to category).
how can i allow a user to add new categories and advantages while creating or updating a record and then updating/saving all of them together with the one click function? as in the user must not know that categories and advantages are separate entities, he must see them as part of the record? user should be allowed to add any amount of categories and advantages in the create/update screen of the record.
any help with these two issues would be greatly appreciated!
Easy, record should accept_nested_attributes_for both category and advantage. You can create new object using client side javascript, watch this episodes( all 3 of them) they contain all you need to know: http://railscasts.com/episodes/196-nested-model-form-part-1
Send me an email if you cant get the javascript there to work, I had to rewrite it, but the idea is the same.
Here is the javascript I used:
//This function adds the fields for the photo association
function add_fields(id, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
var regexp2 = new RegExp("new\\]\\[" + association, "g");
content = content.replace(regexp, new_id);
content = content.replace(regexp2, new_id);
$(id).append(content);
}
def link_to_add_fields(name, id, f, association, partial)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new") do |builder|
render(:partial => partial, :locals => {:form => builder})
end
link_to_function(name, "add_fields( \"#{id}\", \"#{association}\", \"#{escape_javascript(fields)}\" ) " )
end
精彩评论