2016-05-12 94 views
1

在回复的创造,我想更新主板的:用线self.board.update_attributes(:toppid => reply_max.to_i + 1) toppid列,但是这将返回NoMethodError in RepliesController#create undefined method 'update_attributes' for nil:NilClassself.board.update_attributes返回未定义的方法`update_attributes方法

我怎样才能正确地更新: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

任何机会是“未定义的方法”update_attributes“的NilClass”? (它有助于发布完整的错误信息)。 –

+0

@AndrewSchwartz是的,对不起,我也更新了它的帖子。 – aidiah

+0

酷!所以如果它说'NilClass'(或者'nil')没有'update_attributes'方法,那么你认为'self.board'是什么意思,为什么? –

回答

2

看看您致电@reply = @post.replies.create(reply_params)您的回复对象永远不会与板对象关联。

你可能想用build来代替。喜欢的东西:

@reply = @post.replies.build(reply_params) 
@reply.board = @board 
@reply.save 

编辑

从您的意见,似乎是在你希望你的模型中的关系是什么样的脱节和你上面的代码。使用belongs_to意味着您在一个模型与另一个模型之间具有数据库级外键关系。

根据你的意见,你不想要这个。如果确实如此,请摆脱关系并将board改为post。否则,请按照我最初的建议修正表格,然后在您的respond_table中添加board_id。

这里是你会怎么写代表团:

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 

而且,假设你有整列pidtoppid(它看起来像在update_attributes电话),您的to_i使用是不必要的。

+0

我得到的错误:'不能写未知的属性'board_id''突出显示'@reply.board = @ board' – aidiah

+0

声音就像你的模式也搞砸了,你的迁移创建答复表是什么样的? – photoionized

+0

@aidiah,具体来说,您是否在回复表中定义了board_id? – photoionized