2013-05-09 87 views
0

我想這兩個碼控制器內組合成一個在「創建」如何在一種方法下結合這兩個代碼? (軌道3)

class PostcommentsController < ApplicationController 

    def create 
    @micropost = Micropost.find(params[:micropost_id]) 
    @comment = Postcomment.new(params[:postcomment]) 
    @comment.micropost = @micropost 
    @comment.user = current_user 
    if @comment.save 
     redirect_to(:back) 
    else 
     render partial: 'shared/_postcomment_form', locals: { micropost: @micropost } 
    end 
    end 

    def create2 
    @discussion = Discussion.find(params[:discussion_id]) 
    @comment = Postcomment.new(params[:postcomment]) 
    @comment.discussion = @discussion 
    @comment.user = current_user 
    if @comment.save 
     redirect_to(:back) 
    else 
     render partial: 'shared/_postcomment_form', locals: { discussion: @discussion } 
    end 
    end 
end 

我嘗試下「創造」和他們的工作既碼。 我有兩個模型,我將postposment關聯到:micropost和討論。 我想應用正確的「創建」取決於它是微博還是討論。

下面是我用什麼觀點來討論

<%= form_for([@discussion, @comment]) do |f| %> 
<%= f.text_field :comment_content %> 
<button class="btn" type="submit"> 
Comment 
</button> 
<% end %> 

回答

3

現在這樣就不會被測試我給它一個「盲」嘗試,因爲我沒有訪問我的環境代碼,讓我知道,如果它的工作原理或掛起某處...:

def create 
    model = params.has_key?(:micropost_id) ? Micropost : Discussion 
    @object = model.find(params[model.to_s.foreign_key.to_sym]) 
    @comment = Postcomment.new(params[:postcomment]) 
    @comment.write_reflection(@object) 
    @comment.user = current_user 
    if @comment.save 
    redirect_to(:back) 
    else 
    render partial: 'shared/_postcomment_form', locals: { model.to_s.downcase.to_sym => @object } 
    end 
end 

而且在您的評論的模型:

def write_reflection(object) 
    if object.kind_of?(Micropost) 
    self.micropost = object 
    else 
    self.discussion = object 
    end 
end 
+0

我得到這個錯誤:'的SyntaxError在PostcommentsController#創建「語法錯誤,意想不到的 '=',期待keyword_end @ comment.send(model.to_s.downcase)= @ object' – user2159586 2013-05-09 04:43:52

+0

任何想法如何更新代碼?我真的很感激幫助 – user2159586 2013-05-09 05:00:46

+0

編輯我的代碼來反映你的問題! – Raindal 2013-05-09 13:25:41

0

斯巴達ALRE阿迪回答了這個問題,所以我不會重複他的回答。

但我想告訴你,這是一個非常糟糕的主意。這不是一個很好的做事方式。您應該使用多態關聯來表示與討論和微博關係的評論關係。

如果事情在未來發生變化,您正在爲自己設置不必要的重構。

你必須問問自己,你想通過結合這兩種行爲來達到什麼目的?如果有一天你添加另一個模型呢?

def create 
    model = params.has_key?(:micropost_id) ? Micropost : Discussion 

def create 
    model = case params 
    when params.has_key?(:foo) then foo 
    ... # where do you stop? 

你也有你的new行動創造正確的對象,避免nil class錯誤重複這一點。

這不是一種理智的做事方式。

檢查了這一點:http://railscasts.com/episodes/154-polymorphic-association-revised(需要訂閱)

還是這個舊的,但免費的小插曲:http://railscasts.com/episodes/154-polymorphic-association