在创建回复期间,我正在尝试使用行self.board.update_attributes(:toppid => reply_max.to_i + 1)
更新主板的:toppid列,但这会返回NoMethodError in RepliesController#create undefined method 'update_attributes' for nil:NilClass
如何正确更新:toppid
列?
我的其余代码:
reply.rb:
class Reply < ActiveRecord::Base
belongs_to :board
belongs_to :post
after_create :set_pid
def set_pid
reply_max = self.post.replies.maximum(:pid)
board_max = self.board(:toppid)
if board_max.to_i > reply_max.to_i
self.update_attributes(:pid => board_max.to_i + 1)
self.board.update_attributes(:toppid => board_max.to_i + 1)
else
self.update_attributes(:pid => reply_max.to_i + 1)
self.board.update_attributes(:toppid => reply_max.to_i + 1)
end
end
end
replies_controller.rb:
class RepliesController < ApplicationController
def create
@board = Board.friendly.find(params[:board_id])
@post = @board.posts.friendly.find params[:post_id]
@reply = @post.replies.create(reply_params)
@post.touch
redirect_to @board
end
private
def reply_params
params.require(:reply).permit(:name, :email, :subject, :comment, :reply_file)
end
end
routes.rb中:
resources :boards, :path => '' do
resources :posts, :path => 'thread' do
resources :replies
答案 0 :(得分:2)
看看您对@reply = @post.replies.create(reply_params)
的调用,您的回复对象永远不会与董事会对象相关联。
您可能希望使用构建代替。类似的东西:
@reply = @post.replies.build(reply_params)
@reply.board = @board
@reply.save
根据您的评论,您希望模型关系与您的上述代码之间存在脱节。使用belongs_to
意味着您在一个模型与另一个模型之间具有数据库级外键关系。
根据您的评论,您不希望这样。如果情况确实如此,请摆脱关系并将board
委托给post
。否则,通过执行我最初建议的操作并将board_id添加到replies_table来修复表。
以下是编写代表团的方法:
class Reply < ActiveRecord::Base
belongs_to :post
after_create :set_pid
delegate :board, to: :post
def set_pid
reply_max = self.post.replies.maximum(:pid)
board_max = self.board(:toppid) # have no idea what you're trying to do here, but it's also a syntax error, maybe you mean to write: self.board.toppid
if board_max.to_i > reply_max.to_i
self.update_attributes(pid: board_max.to_i + 1)
self.board.update_attributes(toppid: board_max.to_i + 1)
else
self.update_attributes(pid: reply_max.to_i + 1)
self.board.update_attributes(toppid: reply_max.to_i + 1)
end
end
end
另外,假设您有pid
和toppid
的整数列(在update_attributes
调用中看起来很像),则不需要使用to_i
。