2013-05-28 115 views
0

我有一个深层嵌套的资源。目前一切正常,除了当我创造一首歌曲时。由于某些原因,它不会将ARTIST_ID存储在数据库中(显示为NIL)。有人可以帮助我,我是一个新手。深嵌套的资源

第一嵌套存储在专辑表中的ARTIST_ID ...

的routes.rb

resources :artists do 
    resources :albums do 
    resources :songs 
    end 
end 

SONGS_CONTROLLER

class SongsController < ApplicationController 

    respond_to :html, :js 

    def index 
    @artist = Artist.find(params[:artist_id]) 
    @album = Album.find(params[:album_id]) 
    @songs = @album.songs.all 
    end 

    def create 
    @artist = Artist.find(params[:artist_id]) 
    @album = Album.find(params[:album_id]) 
    @song = @album.songs.create(params[:song]) 
     if @song.save 
     redirect_to artist_album_songs_url 
     flash[:success] = "Song Created." 
     else 
     render 'new' 
     end 
    end 

    def new 
    @artist = Artist.find(params[:artist_id]) 
    @album = Album.find(params[:album_id]) 
    @song = Song.new 
    end 

end 

模型

class Artist < ActiveRecord::Base 
    attr_accessible :name 

    has_many :albums 
    has_many :songs 

end 

class Album < ActiveRecord::Base 
    attr_accessible :name, :artist_id 

    belongs_to :artist 
    has_many :songs 

end 

class Song < ActiveRecord::Base 
    attr_accessible :name, :album_id, :artist_id 

    belongs_to :albums 

end 

VIEW(CREATE ,对于歌曲)

<div class="container-fluid"> 
    <div class="row-fluid"> 

    <%= form_for ([@artist,@album, @song]), :html => { :multipart => true } do |f| %> 
     <%= render 'shared/error_messages', object: f.object %> 

     <%= f.text_field :name, placeholder: "name", :class => "input-xlarge"%> 

     <%= f.submit "Create Song", class: "btn btn-primary"%> 

    <% end %> 

    </div> 

</div> 

回答

1

它看起来像你没有在歌曲的任何地方设置artist_id。你正在做的是 - 用album_id和artist_id,你必须选择其中的一个作为父母。就好像你正在缓存歌曲中的artist_id。

我想我会保持他们的方式,你做它,但将其添加到模型。

class Song < ActiveRecord::Base 

    before_save :ensure_artist_id 


    def ensure_artist_id 
    self.artist_id = self.album.artist_id 
    end 

end 

另一种选择是将其设置在控制器中明确

def create 
    @artist = Artist.find(params[:artist_id]) 
    @album = Album.find(params[:album_id]) 
    @song = @album.songs.create(params[:song].merge(:artist_id => @artist.id) 
     if @song.save 
     redirect_to artist_album_songs_url 
     flash[:success] = "Song Created." 
     else 
     render 'new' 
     end 
    end 

但是,这并不觉得干净,可以在其他控制器方法重复。在模型中使用它更好。

+0

真棒谢谢! :) –