Domanda

I've defined three models (User is based on devise).

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

In deals_controller.rb I have:

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

When trying to create new deal I get error:

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 is defined as:

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

Can someone please explain me how to get through this? When I remove "belongs_to: client" in deal model everything works but there is no relationship...

È stato utile?

Soluzione

The reason you get this error is conflict between association and column with the same name (I know it from your deal_params method). You should either remove your client column from deals table, rename this column or rename the belongs_to :client association.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top