0

我定義了三個模型(用戶基於設計)。多個belongs_to和AssociationTypeMismatch

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

這可能是因爲你在'deal'表中有'client'列。我對嗎? –

+0

請粘貼您在參數中收到的來自日誌的創建操作。 –

回答

0

你得到這個錯誤的原因是關聯和列名之間存在衝突(我知道它來自你的deal_params方法) 。 您應該從deals表中刪除client列,重命名此列或重命名belongs_to :client關聯。

+0

謝謝!現在它完美的作品:) – Maciek

相關問題