开发者

Populating form fields for one model with data from another model (in Rails)

Basically, I have an Events model and an EventSets model. Events have EventSets (where applicable) so I can list and group them accordingly in the app (say, a set of Concerts in the Park events where each individual concert event has slightly different attributes, but most of the data are common to 开发者_如何转开发all events in that set).

I have the necessary associations in place so that I can designate an EventSet in Events#new.

In my EventSet model, I have a few columns of 'default' information (common location, common name, etc.) that I'd like to use to pre-populate fields in Events#new.

The EventSet for a new event is designated by a select field (which lists all EventSets, pulled from the EventSets table).

Is there a standard way of handling this in Rails 3 (w/ jQuery)? Or should I roll my own jQuery/AJAX fix to handle it? (I like to stick with the sensible defaults where appropriate.)

Edit for clarification: I'm trying to pre-populate form fields while still in the /events/new view before the form is submitted (as soon as an EventSet is selected). This is necessary because the EventSet-designated 'defaults' will often be overriden for a given Event... they're just a starting point to save on input repetition for the user.


Use the after_initialize callback

def after_initialize :copy_stuff

def copy_stuff
  return unless self.new_record?
  @event_set = EventSet.find(...)
  self.field1 = @event_set.field1
  self.field2 = @event_set.field2
end

You could also do something similar in the Controller.

def new
   @event_set = EventSet.find(...)
   @event = Event.new(:field1 => @event_set.field1, :field2 => @event_set.field2)
   ...
end

EDIT

You'll need to grab those fields via an ajax request

routes.rb

post '/get-eventset-fields' => 'events#event_set_fields', :as => :get_eventset_fields

events_controller.rb

def event_set_fields
  @event_set = EventSet.find_by_id(params[:eventset_id])
  render :json => @event_set.to_json
end

new.html.erb

var mycallback = function(data){
   $('#event_field1').val(data.field1);
   $('#event_field2').val(data.field2);
}

$("#eventset_select").change(function(){
   $.post('<%= get_eventset_fields_path %>', {'eventset_id': $(this).val()}, mycallback, "json"); 
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜