alexZ
alexZ

Reputation: 189

update attribute for rails model

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

Upvotes: 2

Views: 482

Answers (2)

x1a4
x1a4

Reputation: 19485

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.

Upvotes: 1

Kevin Bedell
Kevin Bedell

Reputation: 13404

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!

Upvotes: 2

Related Questions