Rails的attr_accessible 4

时间:2014-03-26 12:27:48

标签: ruby-on-rails ruby ruby-on-rails-4 attr-accessible

您好我需要使用attr_accessible或类似的东西。我是Ruby On Rails的新手

这是我的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 :(得分:0)

Rails4使用强参数而不是attr_accessibles。

有关详细信息,请访问doc

答案 1 :(得分: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
相关问题