简体   繁体   中英

How do i save an associated Object in Rails / Active Record

Lets say i have two models: Team --1---n--> Player In Words: A Team can have many Players. A Player belongs to a Team.

On the page that shows the Team-Data i want to place a link 'create Player'.

In the Players controller, how do I create the Player so that it is associated with the Team, viewed where the 'create Player' link was placed?

Do I have to

1. pass the Team-ID to the 'create Players' controller and

2. look up the Team using the Team-ID and then

3. something like this: @new_player = @team.players.build(...)

Can I use one of the resource routes for the 'create Player' link?

If teams and players will be added via separate forms:

You can either include the team_id in the form for the new player or nest the route to players in the scope of teams and pull the team_id from the url params like params[:team_id] .

Nested players route:

    resources :teams do
      resources :players
    end

In your team/show view (team details page), Create Player link:

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

In the players form:

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

In the Players controller:

    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

Otherwise, see the railscast about nested attributes mentioned by @Antoine for specifying both new team and player details on one form. (I think what you're looking for is the first option with two forms but I could be way off.)

For more information about nested resource routing, see the Rails Routing Guide . To see what routes are available in your application, run rake routes from the command line at the root of your app.

I think nested_attributes can help you.

Watch this railscast about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM