Ruby on rails 在click rails上再添加一组相同的输入
如何添加一组相同的输入(例如教育对象),以便在提交后有两个新的教育对象?更可取的是,需要通过单击位于现有输入集之后的图标来显示新的输入集 这是我的Ruby on rails 在click rails上再添加一组相同的输入,ruby-on-rails,ruby,simple-form,nested-forms,Ruby On Rails,Ruby,Simple Form,Nested Forms,如何添加一组相同的输入(例如教育对象),以便在提交后有两个新的教育对象?更可取的是,需要通过单击位于现有输入集之后的图标来显示新的输入集 这是我的新方法: def new @user = User.new @user.educations.build @user.works.build end 我的看法是: <%= simple_form_for [:admin, @user] do |u| %> <%= u.error_notification %&
新方法:
def new
@user = User.new
@user.educations.build
@user.works.build
end
我的看法是:
<%= simple_form_for [:admin, @user] do |u| %>
<%= u.error_notification %>
<%= u.input :name, label: "Name" %>
<p><b>Photo</b></p>
<%= image_tag(@user.photo_url, size: "80x90",
class:"img-rounded") if @user.photo? %>
<%= u.input :photo, label: false %>
<%= u.input :tel, label: "Tel.:" %>
<h3>Education</h3>
<hr>
<%= u.simple_fields_for :educations do |e| %>
<%= e.input :name, label: "University" %>
<%= e.input :year_started, label: "Started" %>
<%= e.input :year_finished, label: "Ended" %>
<% end %>
# icon `+`
<i class="fa fa-plus fa-2x"></i>
<h3>Work</h3>
<hr>
<%= u.simple_fields_for :works do |w| %>
<%= w.input :name, label: "Name" %>
<%= w.input :year_started, label: "Started" %>
<%= w.input :year_finished, label: "Ended" %>
<% end %>
<%= u.button :submit, "Надіслати" %>
<% end %>
照片
教育类
#图标`+`
工作
最简单的解决方案可能是cocoon gem-如果您想在调用新方法时添加额外的对象,您只需要“构建”更多相关对象:
def new
@user = User.new
2.times do
@user.educations.build
end
@user.works.build
end
这将为您提供两组教育
字段(无需更多代码更改)
如果您想在渲染了新方法之后调用额外的对象/字段,那么您必须按照@Tom Walpole
的建议,使用类似的方法动态地调用这些对象/字段
有一个日期是,但是
--
动态添加字段依赖于一个简单的模式:
按钮/图标按下
对控制器的Ajax调用
控制器为
Ajax响应在DOM中为
添加新的字段
这种(ajax)方法与类似“Railscast”(静态)方法的主要区别在于,它在rails中为
正确地构建了字段。没有黑客工作
#app/views/admin/users/new.html.erb
<%= link_to fa-icon("plus 2x"), admin_new_user_path, remote: true %>
这方面的一大技巧是子索引:Time.now.to\u i
方法。“静态”方法的一个大问题是,每个新字段的id
将与上一个字段完全相同,这会弄乱您的参数:
#app/views/users/new.html.erb
<% if request.xhr? %>
<%= simple_form_for [:admin, @user] do |u| %>
<%= u.simple_fields_for :educations, child_index: Time.now.to_i do |e| %>
<%= e.input :name, label: "University" %>
<%= e.input :year_started, label: "Started" %>
<%= e.input :year_finished, label: "Ended" %>
<% end %>
<% end %>
<% else %>
... your code ...
<% end %>
#app/views/users/new.html.erb
... 你的代码。。。
尽管可能需要调整,但上述方法应该有效
#app/views/users/new.html.erb
<% if request.xhr? %>
<%= simple_form_for [:admin, @user] do |u| %>
<%= u.simple_fields_for :educations, child_index: Time.now.to_i do |e| %>
<%= e.input :name, label: "University" %>
<%= e.input :year_started, label: "Started" %>
<%= e.input :year_finished, label: "Ended" %>
<% end %>
<% end %>
<% else %>
... your code ...
<% end %>