0

我是一个 RoR 新手。我无法创建分配角色的新员工。从下面的服务器日志中,我有点认为记录没有被保存,因为“role_ids”是空白的,但我无法理解为什么传递“role_ids”而不是“role”

我觉得这可能是一个单行修复。请帮我解决问题。在此先感谢您的时间。

Processing by EmployeesController#create as HTML
 Parameters: {"utf8"=>"✓", "authenticity_token"=>"Nf9Ti9vdr0ErvJV3LKoErT6dMoUwWAI5eJVBOUISZxo=", "employee"=> {"name"=>"dvxzv", "role_ids"=>["", "4"], "reports_to"=>"Adam"}, "commit"=>"Create Employee"}
 (0.1ms)  begin transaction
 (0.0ms)  rollback transaction
 Role Load (0.2ms)  SELECT "roles".* FROM "roles" ORDER BY title
 Role Load (0.1ms)  SELECT "roles".* FROM "roles" 
 Rendered employees/_form.html.erb (8.9ms)

请注意上一行中的“role_ids”,我不确定为什么使用 role_ids 而不是 'role' 属性

员工.rb

class Employee < ActiveRecord::Base

attr_accessible :name, :role, :reports_to, :role_ids
validates :name, :presence => true, :length => { :maximum => 20 }

belongs_to :company
has_and_belongs_to_many :roles
end

角色.rb

class Role < ActiveRecord::Base
    attr_accessible :title  
     has_and_belongs_to_many :employees
end

员工控制器.rb

def create
    @employee = User.new(params[:user])
    @role = @employee.roles.build(params[:role]) unless @user.roles.build(params[:role]).blank? 
    respond_to do |format|
      if @employee.save
        format.html { redirect_to @employee, notice: 'Employee was successfully created.' }
        format.json { render json: @employee, status: :created, location: @employee }
      else
        format.html { render action: "new" }
        format.json { render json: @employee.errors, status: :unprocessable_entity }
      end
    end
  end

_form.html.erb

    <%= simple_form_for(@employee, :html => {:class => 'form-horizontal' }) do |f| %>
<fieldset>
    <legend><%= controller.action_name.capitalize %> Employee</legend>  
 <div class="control-group">
 <%= f.label :name, :class => 'control-label' %>
 <div class="controls">
 <%= f.input :name, :label => false %>
  </div>
</div>
<div class="control-group">
 <%= f.label :role, :class => 'control-label' %>
<div class="controls">
 <%= f.association :roles, :collection => Role.all(:order => 'title'), :label_method => :id, :prompt => "Assign role", :label => false %>
    </div>
  </div>
<div class="control-group">
 <%= f.label :reports_to, :class => 'control-label' %>
<div class="controls">
  <%= f.input :reports_to, :collection => [ "Sam", "Adam", "Smith"], :prompt => "Select supervisor", :label => false %>
  </div>
  </div>
  <div class="form-actions">  
<%= f.button :submit %>
</div>
 </fieldset>
<% end %>
4

1 回答 1

0

您可能需要考虑阅读有关嵌套资源的 Rails 指南

如果您想让自己的事情变得更轻松,我强烈建议您研究 Jose Valim 的Inherited Resources gem,它为您解决了很多此类样板文件的肮脏问题。

于 2012-12-05T07:07:59.883 回答