2011-06-07 68 views
1

Rails 3推薦Rest。 例如,我做博客系統。Rails 3:如何在渲染時執行動作:action?

### PostsController 

# show detail 
# tag have lock or unlock status 
def show 
@post = Post.find(params[:id]) 
@tags = @post.tags.select("posts_tags.tag_lock") 
end 

### CommentsController 

# Posts#show has comment form. 
# when you post comment, rails execute this action 
def create 
@post = @post.find(params[:id]) 
begin 
    @post.comments.create!(params[:comment]) 
resucue 
    @tags = @post.tags.select("posts_tags.tag_lock") 
    render 'posts/show' 
end 
end 

如果rails可以使用render執行動作,那麼resucue代碼很簡單。 也許,一個解決方案是做出新的行動。但是,規格沒有新的行動... 有什麼更好?你呢??

對不起,我的英語不好..

回答

0

我想你沒事做你的方式(固定一些拼寫錯誤):

### PostsController 

# show detail 
# tag have lock or unlock status 
def show 
@post = Post.find(params[:id]) 
@tags = @post.tags.select("posts_tags.tag_lock") 
end 

### CommentsController 

# Posts#show has comment form. 
# when you post comment, rails execute this action 
def create 
@post = Post.find(params[:id]) 
begin 
    @post.comments.create!(params[:comment]) 
rescue 
    @tags = @post.tags.select("posts_tags.tag_lock") 
    render 'posts/show' 
end 
end 
+0

您好,感謝!重定向不能保持參數[:評論] ...所以,我想使用渲染。重定向是最好的方式? – terut 2011-06-07 09:18:53

+0

@terut在這種情況下,我認爲你很好,就像你一樣。如果posts/show動作變得更復雜,您可能需要將代碼移動到方法中,並從posts/show和comments/create中調用它,而不是重複自己。 – Ant 2011-06-07 09:38:50

+0

非常感謝!我學習REST。這對我來說很困難。 – terut 2011-06-07 10:21:27