2

In my app, I'm trying to make admin user can edit one attribute of a "post"

The post model is:

class PostsController < ApplicationController

before_filter :admin_user,   only: [:edit, :update]

def edit
  @post = Post.find(params[:id])
end

def update
  @post = Post.find(params[:id])
  if @post.update_attributes(params[:post][:some_attr])
     flash[:success] = "Post updated"
     redirect_to posts_path
  else
    redirect_to root_path
  end
end

The edit view is :

  <% provide(:title, "Edit post") %> 
  <h1>Update the post</h1>

  <div class="row">
    <div class="span6 offset3">
    <%= form_for(@post) do |f| %>
        <%= f.label :some_attr %>
        <%= f.text_field :some_attr %>

    <%= f.submit "Save changes", class: "btn btn-large btn-primary" %>
   <% end %>

When I try to input "123" in the some_attr test_field in edit page, it renders error:

NoMethodError in PostsController#update

undefined method `stringify_keys' for "123":String


Application Trace | Framework Trace | Full Trace
app/controllers/posts_controller.rb:22:in `update'
Request

Parameters:

{"utf8"=>"✓",
 "_method"=>"put",
 "authenticity_token"=>"EdTg+cFBnZY447oSDqSTPfb/PJ6VisJOrQ8kvichDrE=",
 "post"=>{"some_attr"=>"123"},
 "commit"=>"Save changes",
 "id"=>"17"}

What could be the problem? Which piece of the puzzle am I missing?

Thanks

2 Answers 2

2

I believe this line:

@post.update_attributes(params[:post][:some_attr])

should read like this:

@post.update_attributes(params[:post])

To perform an update to @post, you need to pass in the entire hash of attributes for it -- not just the one you're changing.

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's right..I should do more researching before ask
1

The problem is this line:

 if @post.update_attributes(params[:post][:some_attr])

params[:post][:some_attr] is just a value. A field is not specified. If you change the line to

 if @post.update_attributes(params[:post])

the attribute should update as expected.

2 Comments

Thanks! That solved my problem! Actually update_attributes is expecting a hash instead of a string
Yep, exactly. You can pass in an entire hash of attributes to update. Here is some documentation on update_attributes if you're curious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.