2011-10-28 18 views
0

在我relationships_controller我有以下幾點:我是否正確處理這個Rails窗體?

class RelationshipsController < ApplicationController 

    def new 
    @user_id = User.find_by_id(params[:user_id]) 
    @relationship = Relationship.new 
    end 

    def create 
    @relationship = Relationship.new(params[:relationship]) 
    @relationship.rel_id = User.find_by_id(params[:user_id]) 
    @relationship.user_id = current_user 
    if @relationship.save 
     redirect_to root_url, :notice => "Signed Up!" 
    else 
     render "new" 
    end 
    end 
end 

,在我的觀點,我有:

<section id="main"> 
    <%= form_for [@user_id, @relationship] do |f| %> 
    <div class="field"> 
     <%= f.label :type %> 
     <%= select_tag(:type, options_for_select([['Friend', 0], ['Family', 1],['Spouse', 2]])) %> 
    </div> 
    <div class="actions"><%= f.submit %></div> 
    <% end %> 
</section> 

我有幾個問題:

  1. 這是正確的方法處理rel_id和user_id?對我來說這似乎有點笨重。

  2. 我不能得到:類型保存到數據庫,但其他一切。我發現在我的服務器日誌如下:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"z7R4tWSSVHZmFXfh8HocfyuegZ2rwuXXeTLKbR+cLfs=", "type"=>"0", "commit"=>"Create Relationship", "user_id"=>"7"}

這似乎很奇怪我,因爲它要保存類型。

3.如果我在<%= form_for [@user_id, @relationship] do |f| %>行中使用@user_id或@current用戶,這有什麼關係嗎?爲什麼?

回答

1

1)@user_id實際分配的User一個實例,因此分配rel_id,當我想你只需要值的用戶ID(整數),我稱之爲@user 。你可能只是這樣做:

@relationship.rel_id = params[:user_id] 

2)type字段用於與ActiveRecord的STI表,如果你的名字你場type任何其他原因不好的事情發生。嘗試將其更改爲另一個名稱,如relationship_type

3)可能,取決於您的應用程序的設置方式。 @user(_id)和@current_user可能代表不同的用戶。如果你只想讓當前用戶爲自己創建一個關係,那麼你可以使用@current_user(在這種情況下可能不使用嵌套路由)。

+0

'@ user'是人'@ current_user'好友。他們應該始終是不同的用戶。我還沒有編碼檢查。 –

+0

我在Nesting Comments上觀看了Railscast#139,這裏的建議讓我覺得嵌套這是合適的。你有什麼理由不相信嗎? –

+0

在這種情況下嵌套的資源很好。我只是有點不確定你想要用戶@user與current_user相比。 –

1

在rails中調用屬性「type」是一個no-no,因爲它已經在繼承自ActiveRecord :: Base的類上定義了一個類型方法。它用於單表繼承。

最不痛苦的事就是重命名該列「relationship_type」或「好心」,但你可以避開它這樣的,如果你真的需要:

@relationship = Relationship.new(params[:relationship]) 
@relationship[:type] = params[:type] 
+0

我採取了不那麼痛苦的路線,但它仍然沒有儲蓄。我會預料它會抱怨:如果之前輸入的是繼承​​表單ActiveRecord時遇到問題。 –

相關問題