获取嵌套URL中的资源ID Rails 4

时间:2016-07-04 11:25:05

标签: ruby-on-rails routes nested params nested-routes

我要做的是将我的Song实例的“album_id”属性设置为当前正在查看的相册的ID。

例如:

http://localhost:3000/artist_profiles/1/albums/2

在上面的网址中,我想将我创作的歌曲的“album_id”设置为2。

我的songs_controller:

class Albums::SongsController < ApplicationController

  before_filter :set_user_friendships

  def new
  end

  def create
    # Make an object in your bucket for your song
    obj = S3_BUCKET.objects[params[:file].original_filename]

    # Upload the file
    obj.write(
      file: params[:file],
      acl: :public_read
    )

    # Create an object for the song
    @song = Song.new(
        url: obj.public_url,
        name: obj.key
        )

    @song.album_id = Album.find(params[:id])

    # Save the upload
    if @song.save
      redirect_to artist_profile_albums_path(current_user.id), success: 'File successfully uploaded'
    else
      flash.now[:notice] = 'There was an error'
      render :new
    end
  end

  def index
    @user_friendships = current_user.user_friendships.all
    @songs = Song.all
  end

  def song_params
    params.require(:song).permit(:id, :url, :name, :song_title, :album_id)
  end

  def set_user_friendships
    @user_friendships = current_user.user_friendships.all #this is here because of partial UGHHH
  end

end

更具体地说,以下一行:

@song.album_id = Album.find(params[:id])

但是,当我尝试此代码时,我收到以下错误:

Couldn't find Album with 'id'=

如果我尝试:

@song.album_id = Album.find(2).id

或:

@song.album_id = 2

我得到0个错误。

运行rake routes命令后我正在查看的路径是:

/artist_profiles/:artist_profile_id/albums/:id(.:format) 

我如何获得合适专辑的ID?

感谢任何帮助!

更新:

尝试上传歌曲时的日志:

Started POST "/songs" for ::1 at 2016-07-04 07:34:32 -0400
Processing by Albums::SongsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"/pZp493WqiDgkJC72ueK5Wr4eVqdVvWzY43c/ru/OpSt3J9gECwC7nIhszLgyef218sRWsAr9xSZOnH751MUoA==", "file"=>#<ActionDispatch::Http::UploadedFile:0x007ff871c261b0 @tempfile=#<Tempfile:/var/folders/xb/38dybzwn51g3fg4vb7kdgg5m0000gn/T/RackMultipart20160704-11159-5aarh7.mp3>, @original_filename="03 Exit Wounds (Original Mix).mp3", @content_type="audio/mp3", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"03 Exit Wounds (Original Mix).mp3\"\r\nContent-Type: audio/mp3\r\n">, "commit"=>"Upload song"}
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
[AWS S3 200 16.701785 0 retries] put_object(:acl=>:public_read,:bucket_name=>"atmosphere-development",:content_length=>13561000,:data=>#<ActionDispatch::Http::UploadedFile:0x007ff871c261b0 @tempfile=#<Tempfile:/var/folders/xb/38dybzwn51g3fg4vb7kdgg5m0000gn/T/RackMultipart20160704-11159-5aarh7.mp3>, @original_filename="03 Exit Wounds (Original Mix).mp3", @content_type="audio/mp3", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"03 Exit Wounds (Original Mix).mp3\"\r\nContent-Type: audio/mp3\r\n">,:key=>"03 Exit Wounds (Original Mix).mp3")  

  Album Load (0.1ms)  SELECT  "albums".* FROM "albums" WHERE "albums"."id" = ? LIMIT 1  [["id", nil]]
Completed 404 Not Found in 16748ms (ActiveRecord: 0.9ms)

ActiveRecord::RecordNotFound (Couldn't find Album with 'id'=):
  app/controllers/albums/songs_controller.rb:24:in `create'


  Rendered /Users/sethjones/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (5.1ms)
  Rendered /Users/sethjones/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.0ms)
  Rendered /Users/sethjones/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (3.0ms)
  Rendered /Users/sethjones/.rvm/gems/ruby-2.2.1/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (60.4ms)
Cannot render console with content type multipart/form-dataAllowed content types: [#<Mime::Type:0x007ff8731e25a8 @synonyms=["application/xhtml+xml"], @symbol=:html, @string="text/html">, #<Mime::Type:0x007ff8731e22d8 @synonyms=[], @symbol=:text, @string="text/plain">, #<Mime::Type:0x007ff8731dae20 @synonyms=[], @symbol=:url_encoded_form, @string="application/x-www-form-urlencoded">]

2 个答案:

答案 0 :(得分:2)

在聊天讨论后:

params[:album_id].to_i worked.

显然,当他试图像这样分配它时,rails没有将id转换为整数:

@song.album_id = params[:album_id]

-

无论如何,我这样做的方法是通过其父模型创建嵌套模型。

所以不要写这段代码:

@song = Song.new(
    url: obj.public_url,
    name: obj.key
    )

@song.album_id = Album.find(params[:id])

你可以写:

album = Album.find(params[:id])
@song = album.songs.build(url: obj.public_url, name: obj.key)

并且应该将album_id设置为正确的。 (这是我们从查询中获得的album的ID)。

但是这样你就有额外的查询来查找相册,而使用.to_i方法却没有,所以请记住这一点。

答案 1 :(得分:0)

感谢@chaitanya和@Ziv Galili解决问题

将该行更改为:

@song.album_id = params[:album_id].to_i

并将album_id添加到上传表单。