2013-05-28 2 views
0

리소스가 중첩되어 있습니다. 현재 SONG를 만들 때를 제외하고는 모든 것이 잘 작동합니다. 어떤 이유로 데이터베이스에 ARTIST_ID를 저장하지 않습니다 (NIL로 표시). 누군가 나를 도와주세요, 나는 newb입니다.딥 중첩 리소스

제 중첩 점포 앨범 테이블의 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 

MODELS

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 , FOR SONGS)

<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를 설정하지 않은 것 같습니다. 앨범 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

끝내 주셔서 감사합니다! :) –