2014-10-02 44 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