开发者

Rails 3, changing a specific value in a row

This question seems ridiculously easy, but I seem to be stuck.

Lets say we have a table "Books"

Each Book, has a name, description, and a status.

Lets say I want to create link in the show view, that when clicked, solely changes the status (to "read") for example.

So far, I've tried adding a block in the controller, that says:

def read

  @book = Book.find(params[:id])
  @book.status = "Read"
  @book.update_attributes(params[:book])

  respond_to do |format|
    format.html { redirect_to :back}
    format.xml  { render :xml =>开发者_如何学Go @book }
  end

end

Then I've added a link to the view that is like: <%= link_to "Read", read_book_path(@book), :method => :put %>

This isn't working at all. I have added it to my routes, but it doesn't seem to matter.

Any help would be great! Thanks!

-Elliot

EDIT: Forgot to add I'm getting a NoMethodError: undefined method `read_book_path'


You need to define a method called read:

def read
  @book = Book.find(params[:id])

  @book.status = "Read"
  @book.save
end

Then you want <%= link_to "Read", read_book_path(@book), :remote => true %>

and in routes.rb:

resources :books do
  member do
    get 'read'
  end
end

Once that works, mess around with changing the method to :put


If all you're trying to do is set the status attribute on a book and not update any other parameters, then calling update_attributes is unnecessary.

change:

@book.update_attributes(params[:book])

to:

@book.save!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜