Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Nested attribute UJS on a big number of records

View gist:2637961
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
#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
Something went wrong with that request. Please try again.