[Rails3]Not able to call a custom mmethod of post controller outside the post controller
I defined one of my custom method in PostsController as follows:-
class PostsController < ApplicationController
..开发者_StackOverflow.<<other methods truncated from display >>
public
def update_bid_winner (winner_id)
@post.bid_winner_id = winner_id
@post.save
end
end
But when I try to call it from some other controller (BidsController in my case). Where Bid is a nesteded resource of post:-
resources :posts do
resources :bids do
member do
get 'offer_bid'
end
end
end
I tried to call my custom method as follows from the bids controller :-
def offer_bid
@post = Post.find(params[:post_id])
@bid = Bid.find(params[:id])
@post.update_bid_winner(@bid.user_id) <<<<<<<<<< Here goes the call
@post.save
redirect_to post_path(@post)
end
But I get an error saying that undefined method update_bid_winner :-
undefined method `update_bid_winner' for #<Post:0xb68114f4>
Help me out. am I doing anything wrong here? If so , please suggest ways to achieve the same !!
Thanks in Advance.
This is not working because you are calling the method on a Post
object but you have defined the method in the PostsController
class. This method must be defined in the Post model file (app/models/post.rb) for it to work as you want.
Generally, methods that update an object should go in that object's respective class.
PostsController and Post are two different classes. Notice how @post is a Post object: @post = Post.find(params[:post_id])
Define the method in app/models/post.rb
instead of app/controllers/posts_controller.rb
.
Actually the best way to achieve my task is use the following line in the controller itself :-
@post.update_attribute(:bid_winner_id,@bid.user_id)
No need for any new methods in model to update the attribute.
But the inputs provided as other answers really was helpful to enlighten me :). Thanks.
精彩评论