【问题标题】:attr_accessible for Rails 4用于 Rails 4 的 attr_accessible
【发布时间】:2014-03-26 12:27:47
【问题描述】:

您好,我需要使用 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 做些什么感谢您的回答。

【问题讨论】:

  • 一个简单的谷歌搜索会立即有所帮助。

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


【解决方案1】:

您需要为此使用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

【讨论】:

  • ActiveModel::ForbiddenAttributesError in Admin::PostsController#update 我仍然收到此错误,它也包括创建帖子...
  • ` def create @post = Post.new(post_params) respond_to do |format| if @post.save format.html { redirect_to @post,注意:'帖子已成功创建。' } format.json { 渲染动作:'show',状态::created,位置:@post } else format.html { 渲染动作:'new' } format.json { 渲染 json:@post.errors,状态::unprocessable_entity } end end end `创建方法
【解决方案2】:

Rails4 使用强参数而不是 attr_accessibles。

欲了解更多信息,请访问doc

【讨论】:

  • 我做了所有关于强参数的事情,但是当我尝试创建 post ActiveModel::ForbiddenAttributesError 它说禁止我能知道什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多