我有一个用户和推荐模型。用户有几种帐户类型:学生,管理员,推荐人等。学生用户可以分配推荐人来提交推荐。我没有使用Rolify,所以
我目前有:
class Recommendation < ApplicationRecord
belongs_to :assigner, class_name: "User", foreign_key: "user_id"
belongs_to :writer, class_name: "User", foreign_key: "writer_id"
end
class User < ApplicationRecord
has_many :recommendations_via_assigning, class_name: "Recommendation", foreign_key: :assigner_id
has_many :recommendations_via_writing, class_name: "Recommendation", foreign_key: :writer_id
class CreateRecommendations < ActiveRecord::Migration[5.1]
def change
create_table :recommendations do |t|
t.integer :writer_id, foreign_key: true
t.integer :assigner_id, foreign_key: true
t.text :text
t.timestamps
end
add_index :recommendations, :writer_id
add_index :recommendations, :assigner_id
end
end
控制器
def new
@recommendation = current_user.recommendations_via_assigning.build
end
def create
@recommendation = current_user.recommendations_via_assigning.build(recommendation_request_params)
if @recommendation.save
@recommendation.send_invitation_email
flash[:info] = "An email with submission instructions has been sent to the recommender you have invited."
redirect_to user_url
else
render 'new'
end
end
private
def recommendation_request_params
params.require(:recommendation).permit(:assigner_id, :first_name, :last_name, :email, :relationship)
end
def recommendation_content_params
params.require(:recommendation).permit(:writer_id, :first_name, :last_name, :email, :text)
end
我无法保存推荐,因为它需要writer_id,在提交Recommendation#create时将不知道该推荐。需要发生的是,将一封电子邮件发送到所提供的电子邮件地址,邀请教师创建一个帐户,当该帐户注册后,通过ID与教师帐户的writer_id进行推荐。
如何修改现有代码,以使我可以在没有writer_id的情况下通过Recommendation#create?
答案 0 :(得分:0)
推荐的未知属性'user_id',因此我认为我没有正确设置此属性。
是的,您要提供user_id
作为外键,但是推荐表中不存在user_id
列。您需要将assigner_id
重命名为user_id
或删除:foreign_key
设置,因为Rails
可以按照惯例进行查找:
class Recommendation < ApplicationRecord
belongs_to :assigner, class_name: "User"
belongs_to :writer, class_name: "User"
end
尽管有关于has_many :recommendations
的注释。该行实际上要求user_id
表中存在recommendations
。 Rails
无法确定,您是否期望通过撰写或通过分配获得推荐。在这里,您可能想根据docs提供foreign_key
选项:
class User < ApplicationRecord
has_many :recommendations_via_assigning, class_name: "Recommendation", foreign_key: :assigner_id
has_many :recommendations_via_writing, class_name: "Recommendation", foreign_key: :writer_id
end