2014-03-26 68 views
-1

你好,我需要使用attr_accessible或類似that.And我是新的Ruby on Rails的attr_accessible爲Rails 4

這是我post.rb文件

class Post < ActiveRecord::Base 
    has_many :comments 

    attr_accessible :body, :title, :published, :author, :author_id 
    belongs_to :author, :class_name => "AdminUser" 


    validates_presence_of :body,:title 
    scope :published, where(:published => true) 

    def content 
    MarkdownService.new.render(body) 
    end 

    def author_name 
    if author 
     author.name 
    else 
     "Nobody" 
    end 
    end 


end 

我能爲attr_accesible感謝做你的答案。

+2

一個簡單的谷歌搜索會馬上幫助。 –

回答

0

你需要使用Strong Params此:

#app/models/post.rb 
class Post < ActiveRecord::Base 
    has_many :comments 
    belongs_to :author, :class_name => "AdminUser" 

    validates_presence_of :body,:title 
    scope :published, where(:published => true) 

    def content 
    MarkdownService.new.render(body) 
    end 

    def author_name 
    if author 
     author.name 
    else 
     "Nobody" 
    end 
    end 


end 

#app/controllers/posts_controller.rb 
def new 
    @post = Post.new 
end 

def create 
    @post = Post.new(post_params) 
end 

private 

def post_params 
    params.require(:post).permit(:body, :title, :published, :author, :author_id) 
end 
+0

Admin :: PostController ActiveModel :: ForbiddenAttributesError#update 我得到此錯誤stil,其包括創建帖子太... –

+0

'def創建 @post = Post.new(post_params) respond_to do | format | if @ post.save format.html {redirect_to @post,notice:'Post was successfully created。' } format.json {render action:'show',status::created,location:@post} else format.html {render action:'new'} format.json {render json:@ post.errors,狀態::unprocessable_entity} 結束 結束 結束'創建方法 –

0

Rails4使用強參數而不是attr_accessibles。

欲瞭解更多信息請訪問doc

+0

我做了一切有關強參數,但是當我嘗試創建發佈ActiveModel :: ForbiddenAttributesError它說禁止我能做什麼 –