[英]attr_accessible for Rails 4
你好,我需要使用 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 做些什么感謝您的回答。
Rails4 使用強參數而不是 attr_accessibles。
有關更多信息,請訪問文檔
為此,您需要使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.