Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mgswolf
Created May 8, 2012 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgswolf/2637961 to your computer and use it in GitHub Desktop.
Save mgswolf/2637961 to your computer and use it in GitHub Desktop.
Nested attribute UJS on a big number of records
#Artist Model
class Artist < ActiveRecord::Base
has_many :performers, :dependent => :destroy
has_many :musics, :through => :performers
#default_scope order(:name)
def self.find_ordened_artists
Rails.cache.fetch('artists/ordened') { self.select('id, name').order(:name).all }
end
def self.destroy_ordened_artists
Rails.cache.delete('artists/ordened')
end
end
#Music Model
class Music < ActiveRecord::Base
has_many :performers, :dependent => :destroy
has_many :artists, :through => :performers
accepts_nested_attributes_for :performers, :reject_if => lambda { |p| p['artist_id'].blank? },:allow_destroy => true
end
#Music Controller - new action
def new
@music = Music.new
@performers = @music.performers.build
end
#Music _form Partial
<%= form_for [:admin,@music], :class=>"form-inline" do |f| %>
<%= f.error_messages %>
...
<div class="well" id="performers">
<h4><%= t('misc.artist.other') %></h4>
<p>
<%= f.fields_for :performers do |performer_form| %>
<%= render 'performer_fields', :f => performer_form %>
<% end %>
<span class="label label-success">
<i class="icon-plus icon-white"></i>
<%= link_to_add_fields t(:add) + t('misc.artist.one'), f, :performers %>
</span>
</p>
</div>
....
<% end %>
# perfomer_fields partial
<div class='fields'>
<div class="clearfix">
<%= f.label :artist_id, t('misc.artist.one'), class: 'label' %>
<div class="input">
<%= f.collection_select :artist_id, Artist.find_ordened_artists, :id, :name ,:prompt => 'Selecionar Artista' %>
</div>
<span class="label label-important">
<i class="icon-remove icon-white"></i>
<%= link_to_remove_fields t(:remove)+ t('misc.artist.one'), f %>
</span>
</div>
<hr />
</div>
#ApplicationHelper link_to_add_filds method
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to_function(name, ("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
#Application.js add_fields
function add_fields(_2,_3,_4){
var _5=new Date().getTime();
var _6=new RegExp("new_"+_3,"g");
$(_2).parent().before(_4.replace(_6,_5));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment