多个belongs_to和AssociationTypeMismatch

时间:2013-12-23 11:39:58

标签: ruby-on-rails belongs-to model-associations type-mismatch

我已经定义了三个模型(用户基于设计)。

class Deal < ActiveRecord::Base
    belongs_to :user
    belongs_to :client #if i cut this line everything works fine
end

class Client < ActiveRecord::Base
    has_many :deals
end

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

 has_many :deals
end

在deals_controller.rb中我有:

def create
  @deal = current_user.deals.build(deal_params) #ok
    respond_to do |format|
      if @deal.save
        format.html { redirect_to @deal, notice: 'Deal was successfully created.' }
        format.json { render action: 'show', status: :created, location: @deal }
      else
        format.html { render action: 'new' }
        format.json { render json: @deal.errors, status: :unprocessable_entity }
      end
    end
  end

在尝试创建新交易时,我收到错误:

ActiveRecord::AssociationTypeMismatch in DealsController#create
Client(#48283704) expected, got String(#16421928)

Extracted source (around line #31):

    31  @deal = current_user.deals.build(deal_params) #ok
    32    respond_to do |format|

Deal_params定义为:

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def deal_params
      params.require(:deal).permit(:client, :headline, :value, :description, :user_id)
    end
end

有人可以解释一下如何解决这个问题吗?当我在交易模型中删除“belongs_to:client”时,一切正常但没有关系...

1 个答案:

答案 0 :(得分:0)

您收到此错误的原因是关联和具有相同名称的列之间存在冲突(我从您的deal_params方法中知道)。 您应该从client表中删除deals列,重命名此列或重命名belongs_to :client关联。