我有一个包含“user_id”和“post_id”字段的表测试。user_id 我通过 current_user.id 和 post_id 从 post 表中获取。为此,我这样做:在测试控制器中:-
def create
@user = current_user
@test = Test.new(params[:test])
@post = Post.find(params[:id])
@test.post_id = @post.id
@test.user_id = @user.id
respond_to do |format|
@test.save
format.html { redirect_to(:back, :notice => "successfull") }
else
format.html { render :action => "new" }
end
end
在我的模型中,我创建了关联:-
在 test.rb 中:
belongs_to :post
在 post.rb 中:
has_many :test
查看页面是:
= form_for @test, :validate => true do |f|
.span
= f.text_field :email, :placeholder =>"Email Address"
.span
= f.label :name
= f.text_field :name
.span
= f.submit "Save"
user_id 正确保存,但对于 post_id 它给出错误:
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
我该如何解决这个问题?