开发者

Create a link to a defined method?

开发者 https://www.devze.com 2023-03-01 06:11 出处:网络
As my first Rails app, I\'m trying to put together a simple blog application where users can vote on posts. I generated the Blogpost scaffold with a integer column (entitled \"upvote\") for keeping tr

As my first Rails app, I'm trying to put together a simple blog application where users can vote on posts. I generated the Blogpost scaffold with a integer column (entitled "upvote") for keeping track of the vote count.

In the Blogpost model, I created a function:

def self.voteup
  blogpost.upvote += 1
end

On the Blogpost index view, I'd like to create a link that does something like:

link_to "Vote up" self.voteup

But this doesn't seem to work. Is it possible to create a link to a method? If not, can you point me in the right direction t开发者_如何学Co accomplish this?


What you are trying to do goes against the MVC design principles. You should do the upvoting inside a controller action. You should probably create a controller action called upvote. And pass in the post id to it. Inside the controller action you can retrive the post with the passed in ID and upvote it.

if you need serious voting in your rails app you can take a look at these gems


I assume that you need to increment upvote column in blogspots table. Redirection to a method is controllers job and we can give links to controller methods only. You can create a method in Blogposts controller like this:

def upvote_blog
  blogpost = Blogpost.find(params[:id])
  blogpost.upvote += 1
  blogpost.save
  redirect_to blogpost_path
end

In your index page,

<% @blogposts.each do |blogpost| %>
  ...
  <%= link_to "Vote up", :action => upvote_blog, :id => blogpost.id %>
  ...
<% end %>


You can not map Model method to link_to in view. you can create an action in controller to access the Model method and map it using link_to, also if the action is other than CRUD, then you should define a route for the same in route.rb

0

精彩评论

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