Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 获取嵌套URL中资源的ID Rails 4_Ruby On Rails_Routes_Nested_Params_Nested Routes - Fatal编程技术网

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

Ruby on rails 获取嵌套URL中资源的ID Rails 4,ruby-on-rails,routes,nested,params,nested-routes,Ruby On Rails,Routes,Nested,Params,Nested Routes,我想做的是将我的歌曲实例的album_id属性设置为当前正在查看的唱片集的id 例如: 在上面的URL中,我想将我正在创作的歌曲的唱片集id设置为2 My songs\u控制器: class Albums::SongsController < ApplicationController before_filter :set_user_friendships def new end def create # Make an object in your buck

我想做的是将我的歌曲实例的album_id属性设置为当前正在查看的唱片集的id

例如:

在上面的URL中,我想将我正在创作的歌曲的唱片集id设置为2

My songs\u控制器:

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
但是,当我尝试此代码时,会出现以下错误:

Couldn't find Album with 'id'=
如果我尝试:

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

我得到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">]

在聊天室中进行讨论后:

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)
它应该将相册id设置为正确的。这是我们从查询中获得的相册的id


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

多亏了@chaitanya和@Ziv galli,问题才得以解决

将行更改为:

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

并在上传表单中添加了唱片集id。

你能分享路线和日志吗?实际上需要检查你在params[:id]中得到的是哪个id,是唱片集id还是歌曲id?我该如何检查?Rails告诉我ID不存在。当您在此页面上时,您可以在日志中看到参数,然后出错,对吗?所以你可以粘贴到这里,这样你就可以跟踪一些东西,我想你没有在下面的行中传递相册id,比如艺术家\个人资料\相册\路径当前\用户id,:相册\ id=>2
album = Album.find(params[:id])
@song = album.songs.build(url: obj.public_url, name: obj.key)
@song.album_id = params[:album_id].to_i