2014-10-02 47 views
0

我需要將處理後的數據保存在我的模型中,以便將其渲染爲json,但我發現該方法缺少時間以便解決一個愚蠢的問題。如何在軌道模型中保存處理過的數據(獲取NoMethodError)

模型

class Post < ActiveRecord::Base 
    def self.html(html) 
    @html = html 
    end 
end 

控制器

# POST /posts 
    # POST /posts.json 
    def create 
    @post = Post.new(post_params) 
    respond_to do |format| 
     if @post.save 
     @post.html render_to_string(partial: 'post.html.erb', locals: { post: @post }) 
     format.html { redirect_to @post, notice: 'Post was successfully created.' } 
     format.json { 
      render :show, 
      status: :created, 
      location: @post 
     } 
     else 
     format.html { render :new } 
     format.json { render json: @post.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

錯誤

NoMethodError - undefined method `html' for #<Post:0x0000000a5679d0>: 

這是因爲在構建器我想輸出

json.extract! @post, :id, :content, :created_at, :updated_at, :html 

我可以用另一種方式做到這一點,但現在我很好奇,我錯過了什麼?

回答

1

只需添加常規的getter/setter:

class Post < ActiveRecord::Base 
    def html 
    @html 
    end 

    def html=(html) 
    @html = html 
    end 
end 

你也可能需要一個實例方法,因爲你用的Post實例工作(你叫Post.new早期

+0

其實我已經這樣做了,我錯過了錯誤是不同的。 我必須定義一個set_html和html方法才能使它工作,在rails 4中是不是有這樣的標準呢? – 2014-10-02 22:05:12

+0

Thankx你實際上可以在模型上使用'attr_accessor:html' :) – 2014-10-02 22:12:24

+0

@NicolaPeluchetti我返回我的榮譽;) – Ernest 2014-10-02 22:14:48

0

當你定義的方法html。在後期模型中,您正在創建類方法,而不是實例方法。您需要刪除self,並通過添加=

class Post < ActiveRecord::Base def html=(html) @html = html end end