1

What I'm looking to do is set the "album_id" attribute of my Song instance equal to the ID of the album currently being viewed.

For example:

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

In the above URL, I would like to set the "album_id" of the song I am creating equal to 2.

My 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

More specifically, the following line:

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

However, when I try this code I get the following error:

Couldn't find Album with 'id'=

If I try:

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

or:

@song.album_id = 2

I get 0 errors.

The route I am looking at after running the rake routes command is:

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

How would I go about getting the ID of the proper album?

Any help is appreciated!

UPDATE:

My log when attempting to upload the song:

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">]
user3700231
  • 173
  • 2
  • 3
  • 16
  • can you share route and log? – chaitanya Jul 04 '16 at 11:27
  • 1
    Actually need to check which id do you get in params[:id], is it album id or song id? – chaitanya Jul 04 '16 at 11:29
  • How would I go about checking that? Rails is telling me that the ID doesn't exist. – user3700231 Jul 04 '16 at 11:31
  • http://localhost:3000/artist_profiles/1/albums/2 when you are on this page you can see params in log and then error right? so can paste here that so can trace something from that – chaitanya Jul 04 '16 at 11:33
  • i think you are not passing album id in following line like eg. artist_profile_albums_path(current_user.id, :album_id => 2) – chaitanya Jul 04 '16 at 11:35
  • I updated the question so that it includes my log when uploading the song. Thanks for your time! – user3700231 Jul 04 '16 at 11:37
  • i think i got it, you need to send some id like better it would "album_id" from your form, then @song.album_id = Album.find(params[:album_id]) will work, currently create action doesn't getting any id. – chaitanya Jul 04 '16 at 11:43
  • When changing the line to @song.album_id = Album.find(params[:album_id]) I get the same error. Any other ideas? – user3700231 Jul 04 '16 at 11:45
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/116368/discussion-between-chaitanya-and-user3700231). – chaitanya Jul 04 '16 at 11:46

2 Answers2

3

After the discussions in the chat:

params[:album_id].to_i worked.

Apparently rails didn't convert the id to integer when he tried to assign it like this:

@song.album_id = params[:album_id]

--

Anyway the way i do it is by creating the nested model through its parent model.

So instead of writing this code:

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

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

you can write:

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

and it should set the album_id to the correct one. (which is the id of album that we get from the query).

But this way you have an extra query to find the album, and with the .to_i method you don't, so keep that in mind.

Ziv Galili
  • 1,405
  • 16
  • 20
0

Problem solved thanks to @chaitanya and @Ziv Galili

Changed the line to:

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

And added album_id to the upload form.

user3700231
  • 173
  • 2
  • 3
  • 16