【发布时间】:2014-02-13 00:44:14
【问题描述】:
我有一个创建帖子的表单。帖子有一个名为 school_id 的非必填字段。在帖子表单(创建新帖子)上,我有一个复选框。如果选中该复选框,我想将 :school_id 设置为等于也设置为 current_user 的 school_id (由设计创建的对象)。如果选中该复选框,如何将 Post.school_id 设置为等于 current_user.school_id?
我在表单上的复选框传递 :school_id 为 1 并且永远不会更改。这是因为复选框只能接受 1 或 0 的布尔值吗?到目前为止,这是我在表格上的内容:
<%= simple_form_for @post do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_area :content, required: true %>
<% if @school %>
<%= f.label :school_id, "Set school",:class => "checkbox inline" %>
<%= f.check_box :school_id, :value => current_user.school.id %>
<% end %>
<%= f.submit "Submit Post", class: 'btn btn-primary' %>
<% end %>
编辑
后控制器
def create
@school = current_user.school
@post = current_user.posts.build(params[:post])
@post.school_id = current_user.school_id if @school && @post.use_school.present?
end
带有帖子表单的控制器
def index
@post = current_user.posts.build
@school = current_user.school
@post.school_id = current_user.school_id if @school && @post.use_school.present?
respond_to do |format|
format.html # index.html.erb
format.json
format.js
end
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 forms