mercredi 20 mai 2015

Self-Referential Association, possibly because of Foreign-Keys?

I have a class called user that I want build a relationship called affinity to another user. This should then use self-referential association. Here is what I have defined in my User model:

  class User < ActiveRecord::Base
  ...
  has_many :affinities
  has_many :like_users, :through => :affinities
  has_many :inverse_affinities, :class_name => "Affinity", :foreign_key => "user_id"
  has_many :inverse_like_users, :through => :inverse_affinities, :source => :user

And here is the Affinity model:

class Affinity < ActiveRecord::Base
attr_accessible :user_A_id, :user_B_id, :tips_value, :tips_valid, :profile_value, :profile_valid, :value
belongs_to :user
belongs_to :like_user, :class_name => "Users"

Now I can create an affinity just fine. Here is the controller for it:

class AffinitiesController < ApplicationController
...
def create
    @affinity = Affinity.new(params[:affinity])

    if @affinity.save
        redirect_to @affinity
    else
        render 'new'
    end
end

params[:affinity] comes from a form_for in the new view, which I have omitted because it is very long, but it simply asks for all the attr_accessible listed in the Affinity class and then has a submit button. Here is the schema for an affinity:

create_table "affinities", :force => true do |t|
  t.datetime "created_at",    :null => false
  t.datetime "updated_at",    :null => false
  t.float    "profile_value"
  t.boolean  "profile_valid"
  t.float    "tips_value"
  t.boolean  "tips_valid"
  t.float    "value"
  t.integer  "user_A_id"
  t.integer  "user_B_id"
end

I think the problem might be because, although I am creating an affinity, I am not linking it to either of the users i.e. I am not treating neither user_A_id nor user_B_id like a foreign_key. This is my intuition, but I am not certain. Can someone offer some advice? All help is appreciated!

Aucun commentaire:

Enregistrer un commentaire