开发者

Write into db with form_for and method defined in model

I want to implement a like-counter on an object. Everytime the 'I like' Button gets clicked I want to update the database-field of the object.

In the controllers show-view I placed following form:

<% form_for(@book) do |f| %>
 <p>
  <% @book.update_like(@book)%>
  <%= f.submit "I like" %>
 </p>
<% end %>

The update_like method is called in the book.rb model and looks like this:

def update_like(in_book)
    in_book.like_tag = in_book.like_tag + 1;    
end

The update_like methode is called, but the database is not update. I do not grasp what's开发者_如何学C going wrong. Any help is much appreciated.


you don't know the concept of ruby on rails ;)

You can't do it this way, you have to call a controller method to update the database record.

What you're looking for is link_to_remote (this will not work with Rails 3!!)

Have a look at: http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/link_to_remote

So you create a controller let's say "CommentsController" and add an action like "like_it"

Then everything could look like:

Controller:

class CommentsController < ApplicationController

  def like_it

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

    render :nothing => true

  end

end

Model:

class Book < ActiveRecord::Base

  def update_like
    self.like_tag += 1
    self.save

  end

end

In your view:

link_to_remote "I like it!!", :url => { :controller => 'comments', :action => 'like_it', :id => placeCommentIDHere }, :complete => 'alert('You liked it!!');'

I looked at your profile and saw that you're from Switzerland too! Maybe you speak German, if you do so you should read this book (it's free!): http://openbook.galileocomputing.de/ruby_on_rails/

PS: link_to_remote is no longer supported in Rails 3.0 !!

Gruess

Simon ;)


You need save your object

def update_like(in_book)
    in_book.like_tag = in_book.like_tag + 1
    save
end

But the better pratice is do that in your controller.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜