尝试为具有多态关联的模型插入数据

时间:2014-03-30 09:09:39

标签: ruby-on-rails polymorphic-associations

我在尝试将数据插入到具有涉及两个模型的复杂形式的数据库时遇到问题我在Stackoverflow上搜索了每个帖子以找到最佳答案,但是我无法接近它右。

在我的模特中

class ClientIndividual < ActiveRecord::Base
  has_one :client_assignment, :as => :clientassignmentable

  accepts_nested_attributes_for :client_assignment
end

class ClientAssignment < ActiveRecord::Base

  belongs_to :clientassignmentable, :polymorphic => true

end

在我的ClientIndividual Controller中

class ClientIndividualsController < ApplicationController
  before_action :set_client_individual, only: [:show, :edit, :update, :destroy]
  before_filter :authenticate_user!

  def new
    @client_individual = ClientIndividual.new

  end

  def create
   @client_individual = ClientIndividual.new(client_individual_params)

   respond_to do |format|
      if @client_individual.save
        format.html { redirect_to @client_individual, notice: 'Client individual was successfully created.' }
        format.json { render action: 'show', status: :created, location: @client_individual }
      else
        format.html { render action: 'new' }
        format.json { render json: @client_individual.errors, status: :unprocessable_entity }
      end
    end

private
    # Use callbacks to share common setup or constraints between actions.
    def set_client_individual
      @client_individual = ClientIndividual.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def client_individual_params
      params.require(:client_individual).permit(:title, :first_name, :middle_name, 
:last_name, :date_of_birth, :work_phone, :home_phone, :mobile_phone, :email_address, 
:preferred_contact_type, :residential_address, :residential_suburb, :residential_state, 
:residential_postcode, :same_as_residential, :postal_address, :postal_suburb, 
:postal_state, :postal_postcode, :emergency_contact_person, :emergency_phone_no, 
:industry_type, :has_referral, :notes, clientassignmentable_attributes: 
[:assignment_types_id, :employees_id, :start_date, :manager_id, :client_type] )
    end
end

在我的Client_Individual#new view

<%= form_for(@client_individual) do |f| %>
   <div class="add_data_section">

     <%= f.fields_for (:clientassignmentable) do |client_assignment_form| %>
      ........
      ........
      <div class="row_container">
        <div class="field 1" style="width: 409px;">
          <%=client_assignment_form.label :assignment_types_id, "Assignment Type*"%>
        </div>
        <div class="dropdown">
          <label>
             <%= select('client_individual[clientassignmentable]', 'assignment_types_id',  AssignmentType.all.collect {|assignment_type| [assignment_type.name, assignment_type.id ] }, {prompt: 'Select Assignment Type'}, :style =>"width: 264px;")%>
          </label>
        </div>
      </div>
      <div class="row_container">
         <div class="field " style="width: 409px;">
           <%=client_assignment_form.label :start_date, "Assignment Start Date"%>
         </div>
         <div class="inputfield">
            <%=client_assignment_form.text_field :start_date, :class=>'assignmentdatepicker', :style=>'width: 260px;'%>
         </div>
      </div>
      <div class="row_container">
         <div class="field " style="width: 409px;">
           <%=client_assignment_form.label :manager_id, "Manager Appointed*"%>
         </div>
         <div class="dropdown">
           <label>
              <%= select('client_individual[clientassignmentable]', 'manager_id',  Employee.all.select{ |manager| manager.staff_rank_id == 2}.collect{|employee| [employee.first_name + " " + employee.last_name, employee.id ] }, {prompt: 'Select ManagerList'}, :style =>"width: 264px;")%>
           </label>
         </div>
      </div>
      <div class="row_container">
         <div class="field 1" style="width: 409px;">
           <%=client_assignment_form.label :employees_id, "Staff Appointed*"%>
         </div>
         <div class="dropdown">
           <label>
               <%= select('client_individual[clientassignmentable', 'employees_id',  Employee.all.select{ |employee| employee.user_id == current_user_id}.collect{|employee| [employee.first_name + " " + employee.last_name, employee.id ] }, {prompt: 'Select CurrentUser'}, :style =>"width: 264px;")%>
           </label>
         </div>
       </div>
     <%=client_assignment_form.hidden_field :client_type%>
   <% end %>
......
<% end %>

所以我得到的是我有一个ClientIndividual模型,它有一个ClientAssignment模型。因此,ClientAssignment模型具有ClientIndividual FK,因此在创建新的ClientIndividual数据时,我希望在表单上生成新的ClientAssignment数据。因此,在我的控制器中,我宣布我的强大的参数如此

clientassignmentable_attributes: [:assignment_types_id, :employees_id, :start_date, :manager_id, :client_type]

但我点击保存新数据,没有任何内容插入数据库......

然后我检查了我的development.log,它说了以下内容。

Started POST "/client_individuals" for 127.0.0.1 at 2014-03-30 19:58:52 +1100
Processing by ClientIndividualsController#create as HTML
  Parameters: {"utf8"=>"✓",     "authenticity_token"=>"0Z+BJcjQE7oa+uzdo/2sKRPiV01EQDXfedMkLE7pTjg=", "groups"=>{"id"=>"1"},     "client_individual"=>{"clientassignmentable"=>{"assignment_types_id"=>"1",     "start_date"=>"03/31/2014", "manager_id"=>"13", "employees_id"=>"25", "client_type"=>""},     "title"=>"t", "first_name"=>"t", "middle_name"=>"t", "last_name"=>"t", "date_of_birth"=>"",     "work_phone"=>"", "home_phone"=>"", "mobile_phone"=>"",     "email_address"=>"admin@example.com", "residential_address"=>"t", "residential_suburb"=>"t",     "residential_state"=>"t", "residential_postcode"=>"t", "same_as_residential"=>"0",     "postal_address"=>"t", "postal_suburb"=>"t", "postal_postcode"=>"t",     "emergency_contact_person"=>"", "emergency_phone_no"=>"22223", "industry_type"=>"",     "notes"=>""}, "CREATE"=>"Create Client"}
  [1m[36mUser Load (0.7ms)[0m  [1mSELECT `users`.* FROM `users` WHERE `users`.`id` = 1     ORDER BY `users`.`id` ASC LIMIT 1[0m
Unpermitted parameters: clientassignmentable
  [1m[35m (0.3ms)[0m  BEGIN
  [1m[36m (0.2ms)[0m  [1mROLLBACK[0m

我一直得到这个未经许可的参数:clientassignmentable。但是我已经在我的控制器中列入白名单作为一个强大的参数,所以它为什么抱怨???

当然,如果你知道在你面前摆出的正确关联是什么,这也不难理解?

我还能错过什么?!?!我一整天都在这,看起来很困惑......

2 个答案:

答案 0 :(得分:0)

你应该写

fields_for :client_assignment

并在您使用:clientassignmentable

的其他任何地方进行相应更改

进一步阅读:
http://guides.rubyonrails.org/form_helpers.html#understanding-parameter-naming-conventions
http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

要解决未以新形式呈现的字段的问题,请在控制器中执行

@client_individual.build_client_assignment

答案 1 :(得分:0)

我想我的确出错了......

在阅读了建立多态关联的基础知识后,我感到非常尴尬,我意识到我的多态关联是完全错误的!

因此,当我的数据库设计的初始步骤显然完全错误时,我浪费了将近2天的时间来保存表单的数据!多么彻底的浪费!!!

ARRRGGGH !!!!!

现在我需要回到绘图板并找到如何还原它的方法!!!