2012-01-12 51 views
0

假設我有兩個模型:Team --1 --- n - > Player 言辭:一個團隊可以有很多玩家。玩家屬於團隊。我如何在Rails/Active Record中保存關聯對象

在顯示團隊數據的頁面上,我要放置一個鏈接「創建播放器」。

在播放器控制器中,如何創建播放器以使其與團隊相關聯,查看「創建播放器」鏈接的位置?

我必須

通過團隊-ID爲「創建選手」控制器和

2.查詢使用工作組-ID,然後

團隊

是這樣的:@new_player = @team.players.build(...)

我可以使用資源的路線FO之一r'創建玩家'鏈接?

回答

1

我認爲nested_attributes可以幫助你。

手錶this關於它的railscast。

+0

謝謝! 我欣賞這個提示! – 2012-01-13 06:25:38

2

如果球隊和球員將通過單獨的形式添加:

您可以在表單中的新播放器或窩在球隊的範圍,玩家路線TEAM_ID並從URL拉TEAM_ID params像params[:team_id]

嵌套播放器路線:

resources :teams do 
     resources :players 
    end 

在你的團隊/顯示視圖(團隊詳細信息頁),創建播放鏈接:

<%= link_to 'Create Player', new_team_player_path(@team) %> 

在球員構成:

<% form_for [@team, @player] do |f| %> 
    <!-- your form here --> 
    <%- end -%> 

在玩家控制器中:

def new 
     @team = Team.find params[:team_id] 
     @player = Player.new 
    end 

    def create 
     @player = Player.new params[:player] 
     @player.team_id = params[:team_id] # => if just grabbing the id from the url params 
     if @player.save 
     # flash and redirect 
     else 
     # show form again 
     end 
    end 

否則,請參閱關於@Antoine提到的關於嵌套屬性的railscast,以在一個表單上指定新的團隊和玩家詳細信息。 (我認爲你要找的是兩種形式的第一種選擇,但我可能會失敗。)

有關嵌套資源路由的更多信息,請參閱Rails Routing Guide。要查看應用程序中可用的路線,請從應用程序根目錄的命令行運行rake routes

+0

非常感謝您的幫助! 在這樣一個初學者問題上找到一個提示是令人驚訝的很難:-) 在運行Goggles服務器熱點後,我也發現這個教程網站 [ruby-rails-3-model-1-many-association](http:///jonathanhui.com/ruby-rails-3-model-1-many-association) 該網站上有很多好東西。可能對其他新手有用... 但是,無論如何,比你非常! – 2012-01-13 06:19:25

相關問題