我有一个 model 叫 projects,还有一个一个 model 为 users。projects:users 关系为 one:many --------------背景描述完毕---------------
现在在 projects 的表单有 users 列表,可以选择与 project 相关的 user,选了多个 user 以后,提交表单,请问:
希望大侠们能给出一个简单的优雅的实现 小弟刚入门,还请大侠们多多教导!
railscasts 上面找 nested form 看看
#1 楼 @huacnlee 好的,谢谢大侠指点!
如果你 user 不多。就 simple_form,如果多了就考虑换个 select2 或者 chosen
#1 楼 @huacnlee #3 楼 @nickcen 这么搞的
<%= form_for(@project, :html => {:class => 'form-horizontal'} ) do |f| %> <div class="form-group"> <label for="inputName" class="col-sm-2 control-label">名称</label> <div class="col-sm-10"> <%= f.text_field :name ,:class => 'form-control', :id => 'inputName', :placeholder => 'project name' %> </div> </div> <div class="form-group"> <label for="inputDescription" class="col-sm-2 control-label">描述</label> <div class="col-sm-10"> <%= f.text_area :description, :class => 'form-control', :rows => '4', :id => 'inputDescription', :placeholder => 'project description' %> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <!-- rails checkbox --> <% @users.each do |user| %> <div class="checkbox"> <%= check_box_tag 'users[]', user.id%> <%= label_tag user.username %> </div> <% end %> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <%= f.submit "保存", class: "btn btn-primary" %> <%= button_tag "重置", type: :reset, class: 'btn btn-danger' %> </div> </div> <% end %>
后台
def create @project = Project.new(project_params) user_ids = params[:users] # binding.pry user_ids.each do |user_id| user = User.find(user_id) user.update_attribute(:project, @project) end respond_to do |format| if @project.save flash[:success] = '项目添加成功!' format.html { redirect_to projects_path } else format.html { render action: 'new' } end end end