I have the following code
db:
create_table :parties do |t|
t.integer :host_id
t.integer :guests
t.string :description
end
user:
class User < ActiveRecord::Base
has_many :host_parties, class_name: 'Party'
end
party:
class Party < ActiveRecord::Base
belongs_to :host, class_name: 'User', foreign_key: 'host_id'
attr_accessor :user_id
end
parties_controller:
class PartiesController < ApplicationController
def create
@party = current_user.host_parties.create(party_params)
end
private
def party_params
params.require(:party).permit(:host_id, :guests, :description)
end
end
for some reason the create fails with:can't write unknown attribute `user_id'
how can I make rails treat the User.id as host_id?
In has_many
relationship within your User
model, you need to specify the foreign_key
as the default value is user_id
.
The following should work:
class User < ActiveRecord::Base
has_many :host_parties, class_name: Party, foreign_key: :host_id
end