rails4 无法创建关系无法写入未知属性
rails4 fail creating relation can't write unknown attribute
我有以下代码
db:
create_table :parties do |t|
t.integer :host_id
t.integer :guests
t.string :description
end
用户:
class User < ActiveRecord::Base
has_many :host_parties, class_name: 'Party'
end
派对:
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
由于某种原因,创建失败 with:can未写入未知属性“user_id”
如何让 rails 将 User.id 视为 host_id?
在 User
模型中的 has_many
关系中,您需要指定 foreign_key
,因为默认值为 user_id
。
以下应该有效:
class User < ActiveRecord::Base
has_many :host_parties, class_name: Party, foreign_key: :host_id
end
我有以下代码
db:
create_table :parties do |t|
t.integer :host_id
t.integer :guests
t.string :description
end
用户:
class User < ActiveRecord::Base
has_many :host_parties, class_name: 'Party'
end
派对:
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
由于某种原因,创建失败 with:can未写入未知属性“user_id”
如何让 rails 将 User.id 视为 host_id?
在 User
模型中的 has_many
关系中,您需要指定 foreign_key
,因为默认值为 user_id
。
以下应该有效:
class User < ActiveRecord::Base
has_many :host_parties, class_name: Party, foreign_key: :host_id
end