Reputation: 183
I've been looking around and trying to see how I would handle mass-assignment with Rails 4. I know this question has been beaten to death, but from my search, I've only come across answers that require the protected_attributes gem and attr_accessible. Now I'm not sure if that is still the industry standard on this, so I wanted to ask.
I'm using Rails 4.0.1 and I am trying to figure out how I can limit specific parameter updates to admin accounts only.
Here are the parameters: :title, :summary, :content, :status
Now when a user creates a post, they can only update the following attributes: :title, :summary, :content
However, if an admin updates the post, they are able to update :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
Would I be right in assuming that the best way would be to use an operator in the post_params method to check if the user is an admin, and if so, permit a different set of parameters?
Upvotes: 1
Views: 1081
Reputation: 2988
of course, you can use different sets of parameters for different users or for different actions. you would do something like:
def update
if user.is_a? Admin
@post.update(post_params_admin)
else
@post.update(post_params_user)
end
end
def post_params_user
params.require(:post).permit(:title, :summary, :category, :content)
end
def post_params_admin
params.require(:post).permit(:title, :summary, :category, :tags, :content, :user_id, :category_id, :slug, :featured, :views)
end
Upvotes: 3