Assembla home | Assembla project page
 

In this tutorial i will describe the steps needed to mark some uploaded pictures to represent space, see #257.

Model Update

We will need a new field for the Document model.

$ ./script/generate migration SpacePicture

This command will generate a new migration file in RAILS_ROOT/db/migrate/XXX_space_picture.rb, where XXX - will be a number.

class SpacePicture < ActiveRecord::Migration
  def self.up
  end

  def self.down
  end
end 

Edit this file to look like below, we will add a bolean field for_space:

class SpacePicture < ActiveRecord::Migration
  def self.up
    add_column :documents, :for_space, :boolean, :default => false
  end

  def self.down
    remove_column :documents, :for_space
  end
end

Execute

rake migrate

to apply the migration to the DB.

UI Changes

Model is updated, now we need to modify upload form to include this field. File that we need to modify: RAILS_ROOT/app/views/spaces/_document_form.rhtml, add the following lines to this file:

<p><label for="document_for_space">Space picture?</label>
<%= check_box 'document', 'for_space' %></p>

This will add a check box below name field.

Validation

Now we should add validation message in case user will check the checkbox for non-image files. Go on and modify document.rb, change validate method and add below line to the end of method:

errors.add(:for_space, "- you should check only when you upload picture") if for_space && !is_image()

Testing

Something like this:

  def test_create_file
    @request.session = { 'user' => users(:bob) }
    post :create_file, {:id=> 1, :document => {:for_space=>"1", :file => upload_file(get_file('msg-1.txt'))} }
    assert_errors

    post :create_file, {:id=> 1, :document => {:for_space=>"0", :file => upload_file(get_file('msg-1.txt'))} }
    assert_no_errors
  end
  
  def get_file(name)
    "#{RAILS_ROOT}/test/fixtures/files/#{name}"
  end 

in test_helper.rb we will add

  def assert_errors
    assert_tag error_message_field
  end
  
  def assert_no_errors
    assert_no_tag error_message_field
  end
    
  def error_message_field
    {:tag => "div", :attributes => { :class => "fieldWithErrors" }}
  end

Checking:

myhost$ ruby test/functional/spaces_controller_test.rb -n test_create_file
Loaded suite test/functional/spaces_controller_test
Started
.
Finished in 2.282 seconds.

1 tests, 2 assertions, 0 failures, 0 errors

That's all.