[Rails3]无法在后控制器外部调用后控制器的自定义方法
我在 PostsController 中定义了一个自定义方法,如下所示:-
class PostsController < ApplicationController
...<<other methods truncated from display >>
public
def update_bid_winner (winner_id)
@post.bid_winner_id = winner_id
@post.save
end
end
但是当我尝试从其他控制器(在我的例子中为 BidsController)调用它时。其中 Bid 是 post 的嵌套资源:-
resources :posts do
resources :bids do
member do
get 'offer_bid'
end
end
end
我尝试从 bids 控制器中调用我的自定义方法,如下所示:-
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
但我收到一条错误消息,指出未定义的方法 update_bid_winner :-
undefined method `update_bid_winner' for #<Post:0xb68114f4>
帮帮我。我在这里做错了什么吗?如果是这样,请提出实现相同目标的方法!
提前致谢。
I defined one of my custom method in PostsController as follows:-
class PostsController < ApplicationController
...<<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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不起作用,因为您正在调用
Post
对象上的方法,但您已在PostsController
类中定义了该方法。此方法必须在 Post 模型文件 (app/models/post.rb) 中定义,才能按您的需要工作。通常,更新对象的方法应该位于该对象各自的类中。
This is not working because you are calling the method on a
Post
object but you have defined the method in thePostsController
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 和 Post 是两个不同的类。注意 @post 是一个 Post 对象:
@post = Post.find(params[:post_id])
在
app/models/post.rb
中定义方法而不是 <代码>app/controllers/posts_controller.rb。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 ofapp/controllers/posts_controller.rb
.实际上,完成我的任务的最佳方法是在控制器本身中使用以下行:-
模型中不需要任何新方法来更新属性。
但作为其他答案提供的输入确实有助于启发我:)。谢谢。
Actually the best way to achieve my task is use the following line in the controller itself :-
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.