简体   繁体   中英

Rails render partial dynamically

I'm getting a bit crazy with this, I have a Event who has_many Attendants but I haven't been able to create dynamically inside the Event form, I have a partial with the form of Attendant, this works:

<%= form.fields_for :attendants do |form_attendant| %>
  <%= render 'form_attendant', form_attendant: form_attendant %>
<% end %>

for 1 attendant, if I copy-paste that, it works for 2 and so on..

I want a button to do that for me, I've read and tried a loooot.

Option 1: I have tried in js to append that, with:

$("#attendants").append "<%= form.fie ... %>"

but It just print the text and won't render the partial, I have tried with escape_javascript too with no luck.

I'm now trying with:

<%= link_to "Agregar", new_attendant_path, remote: true %>

I have these in attendants/new.js.erb

$('#attendants').append("<%= escape_javascript ( render partial: 'form_attendants' ) %>");

Which actually works and render the partial but now I don't know how to send the local event form so I can make <%= form.fields_for :attendants do |form_attendant| %> ... <%= form.fields_for :attendants do |form_attendant| %> ... inside the partial,

Any help would be appreciated, I'm almost crying

Try nested_form_fields gem

= form_for @user do |f|
  = f.nested_fields_for :videos do |ff|
    = ff.remove_nested_fields_link
    = ff.text_field :video_title
    ..
  = f.add_nested_fields_link :videos

You can change the link text of remove_nested_fields_link and add_nested_fields_link , add classes/attributes, etc...

You can also customize the add/remove functionality, by overriding the

nested_form_fields.js.coffee into your rails JavaScript asset

for more info

https://github.com/ncri/nested_form_fields

<%= form_for @users do |f| %>
 <%= f.fields_for :attendants do |form_attendant| %>
   <%= render 'form_attendant', form_attendant: form_attendant %>
 <% end %>
 <%= f.add_nested_fields_link :attendants %>
<% end %>

partial _form_attendant.html.erb

<%= form_attendant.remove_nested_fields_link %>
<%= form_attendant.text_field :attd_date %>
<%= form_attendant.text_field :attd_time %>

尝试使用茧宝石 ,它将做所有这些事情

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