【发布时间】:2014-03-01 09:20:26
【问题描述】:
我一直在环顾四周,试图了解如何使用 Rails 4 处理批量分配。我知道这个问题已经被打死了,但是从我的搜索中,我只遇到了需要 protected_attributes 的答案gem 和 attr_accessible。现在我不确定这是否仍然是行业标准,所以我想问一下。
我正在使用 Rails 4.0.1,我正在尝试弄清楚如何将特定参数更新限制为仅限管理员帐户。
参数如下: :title, :summary, :content, :status
现在,当用户创建帖子时,他们只能更新以下属性: :title, :summary, :content
但是,如果管理员更新帖子,他们可以更新 :title, :summary, :content AND :status
post_controller.rb
def create
@post = Post.new(post_params)
@post.status = 'pending'
respond_to do |format|
if @post.save
PostMailer.new_post(@post).deliver
format.html { redirect_to @post, notice: 'Post was successfully submitted.' }
format.json { render action: 'show', status: :created, location: @post }
else
format.html { render action: 'new' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def update
@categories = Category.all
respond_to do |format|
@post.slug = nil
if params[:post][:featured]
@image = Imgurruby::Imgur.new('20e2a9ef8542b15873a0dfa7502df0b5')
@image.upload(params[:post][:featured])
params[:post][:featured] = @image.url.to_s
end
if @post.update(post_params)
expire_fragment(@post)
@post.friendly_id
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def post_params
params.require(:post).permit(:title, :summary, :category, :tags, :content, :user_id, :category_id, :slug, :featured, :views)
end
假设最好的方法是在 post_params 方法中使用运算符来检查用户是否是管理员,我是否正确,如果是,允许使用不同的参数集?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 strong-parameters mass-assignment