2
事先道歉,rails新手。问题使用first_or_create检索对象时创建对象的评论
房东有N个评论,评论有1个房东
问:为什么我不能创建一个评论? (返回nil对象)
在landlords_controller#创建: 创建房东或找到一个凭据是否已经在数据库:
@landlord = Landlord.where(:name => params[:landlord][:name],
:city => params[:landlord][:city], :province => params[:landlord][:province]).first_or_create!
当我打电话@landlord.comments[0].setIP request.remote_ip
后来
我收到错误undefined method setIP for nil:NilClass
在地主控制器中提供新的和创建方法
def new
@landlord = Landlord.new
@landlord.comments.build
end
def create
#check if a landlord of the same name already exists and add comments to that db entry
@landlord = Landlord.where(:name => params[:landlord][:name], :city => params[:landlord][:city], :province => params[:landlord][:province]).first_or_create!
#:comment => params[:landlord][:comments_attributes]
@landlord.comments[0].setIP request.remote_ip
if @landlord.save
redirect_to landlords_path
else
end
末
评论控制器是空的,我不是正面的,如果这是一个问题。
仍收到零:NilClass错误。已更新 – Derptacos
。我的错。 –
消除了零:NilClass – Derptacos