Rails 3 - 创建复选框(与 _destroy 相对) [英] Rails 3 - checkbox for create (opposite of _destroy)
问题描述
我有一个与输出字段具有 has_many 关系的查询模型.在我的查询控制器的新函数中,我在查询实例中构建了几个输出字段.在我的表单中,我希望每个复选框都确定是否保存了对象(检查意味着将这个 OutputField 实例保存到数据库中).我怎样才能做到这一点?
我的模型:
类查询:破坏accepts_nested_attributes_for :output_fields结尾类输出字段
我的查询控制器的相关部分.结构是另一种模式.
# GET/queries/new# GET/queries/new.json定义新@query = Query.newStructure.columns.each 做 |column|@query.output_fields.build( :table_name => Structure.table_name, :column_name => column.name )结尾response_to do |格式|format.html # new.html.erbformat.json { 渲染:json =>@询问 }结尾结尾
最后说说我的看法.现在我正在将复选框链接到 destroy 属性,我认为这与我想要的完全相反.
<%= form_for(@query) do |f|%><%= f.fields_for :output_fields 做 |builder|%><div class="field"><%= builder.check_box :_destroy %><%= builder.label :_destroy, builder.object.column_name %>
<%结束%><div class="actions"><%= f.submit %>
<%结束%>
如果不明显,我正在尝试为简单的查询构建器生成用户界面.这是我的第一个 rails 应用程序,因此感谢您提供任何建议.
默认情况下,check_box 表单助手的值是将 checked_value 设置为1",将 unchecked_value 设置为0".因此,要反转销毁复选框的行为,只需切换这些值即可.
<%= builder.check_box :_destroy, {}, '0', '1' %>
I have a Query model with a has_many relationship to OutputFields. In my query controller's new function I build several OutputFields within the query instance. In my form, I want each checkbox to determine whether the object is saved (a check means save this instance of OutputField to the database). How can I do this?
my models:
class Query < ActiveRecord::Base
attr_accessible :description, :name
has_many :output_fields, :dependent => :destroy
accepts_nested_attributes_for :output_fields
end
class OutputField < ActiveRecord::Base
attr_accessible :query_id, :column_name, :table_name
belongs_to :query
end
relevant sections of my queries controller. Structure is another model.
# GET /queries/new
# GET /queries/new.json
def new
@query = Query.new
Structure.columns.each do |column|
@query.output_fields.build( :table_name => Structure.table_name, :column_name => column.name )
end
respond_to do |format|
format.html # new.html.erb
format.json { render :json => @query }
end
end
Finally, my view. Right now I'm linking the checkbox to the destroy attribute, which I think will do the exact opposite of what I want.
<%= form_for(@query) do |f| %>
<%= f.fields_for :output_fields do |builder| %>
<div class="field">
<%= builder.check_box :_destroy %>
<%= builder.label :_destroy, builder.object.column_name %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
If it's not obvious, I'm trying generate a user interface for a simple query builder. This is my first rails app, so any advice is appreciated.
By default the value of the check_box form helper is to set the checked_value to '1' and the unchecked_value to '0'. So to reverse the behaviour of the destroy checkbox, just switch these values around.
<%= builder.check_box :_destroy, {}, '0', '1' %>
这篇关于Rails 3 - 创建复选框(与 _destroy 相对)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!