我正在尝试实现以下场景。基本上我有2个模型
主题
选项
在我的表单中,我试图让用户使用设置选项填充选项表,例如我的 html.erb 可能如下所示:
<%= form_for [:admin, @options],:class => 'form' do |f| %>
<div class="form-group">
<%= f.label :option[:color] %>
<%= f.text_field :option[:color], :class => 'form-control' %>
</div>
<div class="form-group">
<%= f.label :option[:header_title] %>
<%= f.text_field :option[:header_title], :class => 'form-control' %>
</div>
<div class="form-group">
<%= f.label :option[:footer_copy] %>
<%= f.text_field :option[:footer_copy], :class => 'form-control' %>
</div>
<div class="form-group">
<%= f.submit :value => 'Update', :class => 'btn btn-primary' %>
</div>
<% end %>
上述场景将向选项表添加 3 行,每行都具有相同的 theme_id。
但我不确定用于 Controller (获取和发布操作)、模型和 View 的语法
任何帮助将不胜感激!
谢谢
编辑
保存上述表单示例后,它将在选项表中保存为 3 个单独的行,例如:
主题id |姓名 |值(value)
1 | “颜色” | “绿色”
1 | "header_title"| “主题标题在这里”
1 | "footer_copy"| “lorem ipsum bla bla”
最佳答案
您需要在客户端动态生成这些字段
class Theme < ActiveRecord::Base
has_many :options
accepts_nested_attributes_for :options, allow_destroy: true
end
class Option < ActiveRecord::Base
belongs_to :theme
end
class ThemesController < ApplicationController
def new
@theme = Theme.new
3.times { @theme.options.build }
end
private
def theme_params
params.require(:theme).permit(:title, options_attributes: [:id, :name, :value, :_destroy])
end
end
在您的 views/themes/_form.html.erb 添加
<%= form_for(@theme) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<%= f.fields_for :options do |builder| %>
<%= render 'option_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add", f, :options %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
创建一个新的局部 View /主题/_option_fields.html.erb
<fieldset>
<%= f.select :name, [["Color", "color"], ["Header", "header_title"], ["Footer", "footer_copy"]] %>
<%= f.text_field :value, placeholder: "Value" %>
<%= f.hidden_field :_destroy %>
<%= link_to "remove", '#', class: "remove_fields" %>
</fieldset>
在你的 themes.coffee 文件中添加
$(document).on "ready page:load", ->
$('form').on 'click', '.remove_fields', (event) ->
$(this).prev('input[type=hidden]').val('1')
$(this).closest('fieldset').hide()
event.preventDefault()
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
在 application_helper.rb 添加
module ApplicationHelper
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
end
结果
关于ruby-on-rails - Rails 4 以类似于 wordpress 选项表的方式保存字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37009066/