简体   繁体   中英

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"); 
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM