2016-05-12 87 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