ruby-on-railsrubyruby-on-rails-4attr-accessible

attr_accessible for Rails 4


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.


Solution

  • 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