ruby - Rails - multiple association unknown attribute -
i'm making api in rails, , has model called match has 2 association user model defined as
belongs_to :user_a, class_name: 'user', foreign_key: 'user_a' belongs_to :user_b, class_name: 'user', foreign_key: 'user_b'
in user model:
has_many :matches
in match controller spec, i'm doing following:
before(:each) user = factorygirl.create :user api_authorization_header user.auth_token @match_attribs = factorygirl.attributes_for :match post :create, { match: @match_attribs } end
and tests fails "unknown attribute: user_id"
if make change post:
post :create, { user_a: user.id, user_b: user.id, match: @match_attribs }
then still giving me unknown attribute.
edit: scheme matches:
create_table "matches", force: true |t| t.integer "user_a" t.integer "user_b" t.datetime "created_at" t.datetime "updated_at" end add_index "matches", ["user_a"], name: "index_matches_on_user_a" add_index "matches", ["user_b"], name: "index_matches_on_user_b"
thanks help
rails , sql convention dictate foreign keys should end in _id
, e.g. user_a_id
, user_b_id
. since rails built around "convention on configuration," convention make code simpler. if change field names, code becomes:
match.rb
belongs_to :user_a, class_name: "user" belongs_to :user_b, class_name: "user"
user.rb
has_many :matches_a, class_name: 'match', foreign_key: 'user_a_id' has_many :matches_b, class_name: 'match', foreign_key: 'user_b_id' def matches match.where("user_a_id = :id or user_b_id = :id", id: id) end
using method way make kind of relation. way return relation can further query, while concatenating other 2 relations (matches_a + matches_b
) return array.
Comments
Post a Comment