2
votes

I'm trying to make an app to make photo albums that belong to many users, and users to have multiple photo albums. However, my @user.album.count doesn't seem to change whenever I try to create an album.

album/new.html.erb

<%= form_for (@album), url: user_albums_path, :html => { :id => "uploadform", :multipart => true } do |f| %>
<div>
    <%= f.label :name %>
    <%= f.text_field :name %>


    <%= f.label :description %>
    <%= f.text_area :description %>

    <br>

    <%=f.submit %>
</div>
<% end %>

albums controller

class AlbumsController < ApplicationController

    def index
      @user = User.find(params[:user_id])
      @albums = @user.albums.all

      respond_to do |format|
        format.html
        format.json { render json: @albums }
      end
    end

    def show
      @albums = Album.all
      @album = Album.find(params[:id])
      @photo = Photo.new
    end

    def update
    end

    def edit
    end

    def create
      @user = User.find(params[:user_id])
      @album = @user.albums.build(params[:album])
      respond_to do |format|
        if @album.save
          format.html { redirect_to user_path(@user), notice: 'Album was successfully created.' }
          format.json { render json: @album, status: :created, location: @album}
        else
          format.html { render action: "new" }
          format.json { render json: @album.errors, status: :unprocessable_entity }
        end
      end 
    end

    def new
      @user = User.find(params[:user_id])
      @album = Album.new
    end

    def destroy
    end

end

models

#album model
class Album < ActiveRecord::Base
  attr_accessible :avatar, :name, :description
  has_many :user_albums
  has_many :users, :through => :user_albums
  has_many :photos
end


#user model
class User < ActiveRecord::Base

  has_secure_password
  attr_accessible :email, :name, :password, :password_confirmation
  validates_presence_of :password, :on => :create

  validates_format_of :name, :with => /[A-Za-z]+/, :on => :create
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
  validates_length_of :password, :minimum => 5, :on => :create

  has_many :user_albums
  has_many :albums, :through => :user_albums
  accepts_nested_attributes_for :albums

end

  #photo model (not up to there yet)
  class Photo < ActiveRecord::Base
    belongs_to :album
  end

config/routes

Pholder::Application.routes.draw do
resources :users do
  resources :albums 
end

resources :albums do
  resources :photos
end

root :to => "users#index"

this is my console

Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2012-10-01 17:41:59 -0400 Served asset /application.js - 304 Not Modified (0ms) [2012-10-01 17:41:59] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true

Started POST "/users/13/albums" for 127.0.0.1 at 2012-10-01 17:42:11 -0400 Processing by AlbumsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"ttqQnEt1KFuwvYRU6MuOLgc5UprSE/zMzGMuzzZiZiE=", "album"=>{"name"=>"fdsafds", "description"=>"fdafdsfafdsfadsfsdsa"}, "commit"=>"Create Album", "user_id"=>"13"} User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", "13"]] (0.0ms) begin transaction SQL (0.3ms) INSERT INTO "albums" ("created_at", "description", "name", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Mon, 01 Oct 2012 21:42:11 UTC +00:00], ["description", "fdafdsfafdsfadsfsdsa"], ["name", "fdsafds"], ["updated_at", Mon, 01 Oct 2012 21:42:11 UTC +00:00]] (5.6ms) commit transaction Redirected to http://localhost:3000/users/13 Completed 302 Found in 9ms (ActiveRecord: 6.0ms)

1
What does the logs says in your console ? Is the POST request processed but the albums controller ? I guess it ends with a ROLLBACK, which means the record could not be saved. You can track the error by printing @album.errors in your controller after saving itpjam
hey pjam. sorry for the delay. I added my console contents. It looks like it works but when it redirects to the user#show after form submission, I have a @user.albums.count in the view but it says 0bigpotato
Could you paste your UserAlbum model ? It seems the problem is now about the associations between the model. The data is correctly inserted in the DataBase but it should also insert a row in the album_users table with the id of the newly created album and the id of the user (13 here).pjam
apparently the albums are being posted/saved. I manage to print out the existing ones in my database without trouble. I think the issue is the album relationship with the users. Here is what I get when I type <%= @albums %> with @albums set to Album.all in my controller. [#<Album id: 1, name: "", created_at: "2012-09-28 03:54:28", updated_at: "2012-09-28 03:54:28", description: nil>, #<Album id: 2, name: "", created_at: "2012-09-29 22:28:09", updated_at: "2012-09-29 22:28:09", description: "">,...bigpotato
By the way if somhehow your app is on github, just paste the link here, I'll give it a look locally to find the issue.pjam

1 Answers

2
votes

Ok I found the problem. As you are creating the album through the user, with the build method

@album = @user.albums.build(params[:album])

then it's the user you have to save,

@user.save

So your new create method is

def create
  @user = User.find(params[:user_id])
  @album = @user.albums.build(params[:album])
  respond_to do |format|
    if @user.save
      print @album.errors
      format.html { redirect_to user_path(@user), notice: 'Album was successfully created.' }
      format.json { render json: @album, status: :created, location: @album}
    else
      format.html { render action: "new" }
      format.json { render json: @album.errors, status: :unprocessable_entity }
    end
  end
end