Ruby on Rails Thursday, May 28, 2015

Good time.
Try to solve next problem. I have two models: user and dispute. User has many disputes and dispute must contain two users (claimant with :claimant_id and indicted with :indicted_id). So instead :user_id in dispute model I have two columns with foreign_keys 

class User
   has_many :disputes  end  
class Dispute      belongs_to :claimant, class_name: 'User', :foreign_key => :claimant_id      belongs_to :indicted, class_name: 'User', :foreign_key => :indicted_id  end

Schema is next:

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "password_digest"
    t.string   "remember_token"
    t.boolean  "admin",           default: false
  end

  create_table "disputes", force: true do |t|
    t.integer  "post_id"
    t.string   "reason"
    t.integer  "claimant_id"
    t.integer  "indicted_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

Relationships like @dispute.claimant.name or @dispute.indicted.email working pretty well. But reverse relationships are troubles and sorrows
The problem is:
In dispute_controller i create a method which find all user disputes, where user is a indicted in dispute

  def disputes_list
    @user = current_user
    @disputes = @user.disputes.where(indicted_id: @user.id) # also used @user.disputes.where("claimant_id = ?", @user.id)
    @disputes = @disputes.paginate(page: params[:page])
  end

This method return me a headache: 

ActiveRecord::StatementInvalid in Disputes#disputes_list

SQLite3::SQLException: no such column: disputes.user_id: SELECT COUNT(*) FROM "disputes"  WHERE "disputes"."user_id" = ? AND "disputes"."indicted_id" = 1

How I think, when I build a call like @user.disputes ActiveRecord try to find  a column with user_id in dispute model, but I have :claimant_id and :indicted_id instead :user_id
It's my first time with using foreign_key, so I can make mistake in design. Please help me fix it. Thank you

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/b7dfaa4b-5a55-43ad-91b2-0325caf9010c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment