2017-04-16 42 views
0

另一個新問題。樂隊has_many專輯。我發現了錯誤:has_many構建AssociationTypeMismatch錯誤

ActiveRecord::AssociationTypeMismatch (Band(#70076964285020) expected, got "1" which is an instance of String(#12787800)):
app/controllers/albums_controller.rb:20:in `create'

...這是#創建構建線

專輯控制器

def new 
    binding.pry 
    @band = Band.find(params[:band]) 
    authorize @band, :admin? 

    @album = Album.new 

    respond_to do |format| 
    format.js 
    end 
end 

def create 
    binding.pry 
    @band = Band.find(params[:album][:band].to_i) 
    authorize @band, :admin? 

    @album = @band.albums.build(album_params)  

    if @album.save 

    @albums = @band.albums 
    #@eps = @band.eps 
    #songs = @band.songs 

    respond_to do |format| 
     format.js 
    end 
    else 
    @fail = "fail" 

    respond_to do |format| 
     format.js 
    end 
    end 
end 


def album_params 
    params.require(:album).permit(:band, :album_name, :album_release_date, :etc) 
end 

形式:

<%=simple_form_for(@album, remote: true, :authenticity_token => true, format: :js) do |f| %> 

    <%= f.hidden_field :band, :value => @band.id %> 

    <%= f.input :album_name %> 

    <%= f.input :album_release_date %> 

    <%= f.input :etc %> 

    <div id="albumsubmit"> 
     <div class="form-actions"> 
     <%= f.button :submit, "Create Album", class: "btn btn-primary" %> 
     </div> 
    </div> 

模式

create_table "albums", force: :cascade do |t| 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.bigint "band_id" 
    t.string "album_name" 
    t.string "album_release_date" 
    t.index ["band_id"], name: "index_albums_on_band_id" 
end 

回答

0

當你傳遞給保存方法PARAM與擁有的has_many協會,他期望的 「帶」 的情況下,只需設置帕拉姆名稱band_id

這裏:

<%= f.hidden_field :band, :value => @band.id %> 

到:

<%= f.hidden_field :band_id, :value => @band.id %> 

這裏:

params.require(:album).permit(:band, :album_name, :album_release_date, :etc) 

到:

params.require(:album).permit(:band_id, :album_name, :album_release_date, :etc) 
+0

也在這裏'@band = Band.find(PARAMS [:相冊] [:樂隊] .to_i)':) –

+0

對上了,謝謝。我在10分鐘之前通過刪除:params中的band來解決它,我猜測它與我的關聯混合在一起,並且似乎band_id字段會從構建中自動推斷出來。 – fdsaevad