attr_accessible for Rails 4

388 Views Asked by At

Hello I need to use attr_accessible or something like that.And I am new on Ruby On Rails

That is my post.rb file

    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

what can I do for attr_accesible thanks for your answers.

2

There are 2 best solutions below

2
Richard Peck On BEST ANSWER

You'll need to use Strong Params for this:

#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
1
Debadatt On

Rails4 uses strong parameters rather than attr_accessibles.

For more info visit doc