Today, I've been working to get attachment_fu working with rmagick on Windows. At first, it wasn't uploading the file properly and after much Googling implemented these changes to get it working.
1. I added a pause to my #create in order to allow Windows time to catch up. In short, Ruby is moving faster than the Windows file system, and it was trying to create a record for a file that didn't exist yet. Here's what I did: def create
@upload = Upload.new(params[:upload])
sleep 5 ## <<-- pauses so Windows can catch up. Probably would be
## smart to make this something like sleep 5 if OS == Windows
## obviously, that's not the right syntax.
if @upload.save
flash[:notice] = 'Upload was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new'
end
end
I am fully aware that this is a hack, but it gets the job done.
2. I continued to get the error message "Size is not included in the list". Long story short, this is the error message attachment_fu returns when the file size exceeds the limit set in the model. In addition, it provides this message if no file is provided at all which is a duplicate error because validates_as_attachment is already doing a validates_presence_of against the size.
So, in order to create some better error messaging, and following the notions of how to hack a plugin from this blog post, I created a new plugin called attachment_fu_hacks and in init.rb added this code:klass = Numeric
klass.class_eval do
def to_human
units = %w{B KB MB GB TB}
e = (Math.log(self)/Math.log(1024)).floor
s = "%.1f" % (to_f / 1024**e)
s.sub(/\.?0*$/, ' ' + units[e])
end
end
klass = Technoweenie::AttachmentFu::InstanceMethods
klass.module_eval do
# overrides attachment_fu.rb:342 b/c to provide better error messages
def attachment_attributes_valid?
attr_name = :size
enum = attachment_options[attr_name]
val = send(attr_name)
if !enum.nil? && !val.nil? && !enum.include?(val)
err_msg = enum.end.to_human
errors.add attr_name, "of file is too big (must be less than #{err_msg})"
end
attr_name = :content_type
enum = attachment_options[attr_name]
val = send(attr_name)
if !enum.nil? && !val.nil? && !enum.include?(val)
err_msg = enum.join(', ').gsub(/image\//, '.') unless enum.nil?
errors.add attr_name, "is not supported (must be #{err_msg})"
end
end
end
klass = Technoweenie::AttachmentFu::ClassMethods
klass.module_eval do
# overrides attachment_fu.rb:106 b/c i don't think it's necessary
# to evaluate size or content_type if there is no file
def validates_as_attachment
validates_presence_of :filename
validate :attachment_attributes_valid?
end
end
I recognize that there might be a more idiomatic Ruby way to write attachment_attributes_valid?, but I prefer this because it's very clear as to what's going on.
attachment_fu (with rmagick) on windows
2
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Issue with has_many and Array.empty?
I've posted a narrative of my issue on the Google Rails Group:
/app/controllers/document_groups_controller.rb
def show
@document_group = DocumentGroup.find(params[:id])
@journal = Journal.find(params[:journal_id])
@document_group_templates = @document_group.document_templates
@logger = RAILS_DEFAULT_LOGGER
#
# this is the money line: comment it out and @document_group_templates.empty?
# is true in the view. leave it in, and it's false. true is correct.
#
@logger.debug "###### --->" + @document_group_templates.inspect
#
# it turns out that this triggers the SQL to be run by Rails that acutally
# populates the @document_group_templates Array.
#
render :action => :show, :layout => 'ajax_div'
end
/app/views/document_groups/show.rhtml
#
#@document_group_templates.empty? evaluates to true without the inspection above
#
<% if !@document_group_templates.empty? %>
#
# now, what's interesting is that if i change this to
#
# if @document_group_templates.count > 0
#
# that also triggers the SQL to be run. but, interestingly, #size does not
# trigger the SQL.
#
<ul>
<%
@document_group_templates.each do |child|
%><li><%= link_to child.name, :controller => :template, :action => :show, :id => child.id %><%
end
%>
</ul>
<% end %>
/app/models/document_group.rb
class DocumentGroup < ActiveRecord::Base
has_many :document_templates, :order => :document_group_position
acts_as_tree :counter_cache => true
end
/app/models/document_template.rb
class DocumentTemplate < ActiveRecord::Base
belongs_to :document_group, :counter_cache => true
acts_as_list :scope => :document_group, :column => :document_group_position
end
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
How to call render :partial properly
At some point, you may be going bananas because you're getting this error:NoMethodError in DocumentController#new
undefined method `include?' for :new:Symbol
and the problem is that you're doing this somewhere:render :partial => :new
instead of this:render :partial => 'new'
This error is spawned by the method partial_pieces in /ruby/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_view/partials.rb:90 which is trying to figure out if the partial you're calling is in the directory of the current controller, or some other directory. Here's that code:89 def partial_pieces(partial_path)
90 if partial_path.include?('/')
91 return File.dirname(partial_path), File.basename(partial_path)
92 else
93 return controller.class.controller_path, partial_path
94 end
95 end
The error comes from line 90. Seems like if this were inserted at line 89.5, then this problem could be handled more gracefullypartial_path = partial_path.to_s if partial_path.is_a? Symbol
given the fuzzyness of symbols and strings, it would seem to make sense to me.
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
How to Avoid and Infinite Loop with before_save and after_save
I have an entity that looks something like this:
journal
author_first_name
author_last_name
journal_name
journal_email_address
where
journal_name = author_first_name + ' ' + author_last_name
journal_email_address = journal_name + '-' id
I had journal_name and journal_email_address implemented as attributes on the Journal model, but the time came along where, for various reasons, it has become valuable to also store that information in the database. So, what I thought I’d do, in app/models/journal.rb:
def make_journal_name
self.journal_name = self.author_first_name + ' ' + self.author_last_name
end
def make_inbound_email
self.inbound_email = self.journal_name.gsub(/[^a-zA-Z0-9]/, '') + '-' + self.id.to_s
end
def before_save
make_journal_name
make_inbound_email
end
which works fine in the case of an update of an existing record. However, it does not work in the case of a creation of a new record because before saving self.id does not exist. The result was my e-mail addresses are looking like “SallyJones-” as opposed to “SallyJones-64”.
Okay, I thought, “since I need an ID to work with I’ll move this to after_save,” like so:
def after_save
make_journal_name
make_inbound_email
self.save
end
but that creates an infinite loop.
The solution to this problem is to use an undocumented method: update_without_callbacks.
def after_save
make_journal_name
make_inbound_email
self.update_without_callbacks
end
update_without_callbacks is an instance method on ActiveRecord::Base, but for some reason it’s undocumented. In fact, it explicitly has :nodoc set in the source, although I can’t figure out why. To me, it seems that having more documented is better than having less.
2
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
The Rails Way
A big part of using Rails is understanding that if you conform to "The Rails Way" things are much easier. Of course, The Rails Way might not work for your project, and in that case, Rails might not be the right framework choice. But, you have to learn The Rails Way in order to know.
I can't claim to explain The Rails Way completely, but I've been helping a new (to Rails) developer on my team get up and running, so I've been having to coach him to see The Rails Way.
I started by talking about "entities". An entity is a thing like a "widget"...some object in our application domain that we need to represent. By convention, the names of the database table, unit tests, models, controllers, views, layouts and helpers must always coordinated in Rails to the name of the entity. So, with our "widget" entity, this is how they should be:
- DB Table: widgets
- Model: app/models/widget.rb
- Controller: app/controllers/widgets_controller.rb
- View: app/views/widget/...
- Layout: app/views/layouts/widgets.rhtml
- Helper: app/helpers/widgets_helper.rb
The beautiful thing about Rails is that by using generators, this gets managed for you. Here’s the approach I always take when creating an entity. This can be done through an IDE (such as RadRails, which is what I use) or on the command line...I’ll use the command line here:
- cd path/to/rails/app
- ruby ./script/generate model Widget which will generate your model file and your migration file with the proper table name.
- Open up the migration, add the appropriate columns and save.
- rake db:migrate to apply your migration to the DB.
- ruby ./script/generate scaffold Widget which will create your controller, views, layout and helper.
Generators create a starting point to start editing, and it also gets all the file names correct. Let’s talk about the editing that needs to happen. Personally, I always do my editing in this order:
- Migration
- Model
- Controllers
- Views
- Layouts
This makes the most sense to me because I’m starting with the raw data, and working my way forward to what the user sees on the web page.
A little background on controllers (a good article to read is this: http://www.softiesonrails.com/search?q=rest+101): Your standard CRUD controller has 8 actions:
- Create (Create): /widgets/create
- Show (Read): /widgets/show/:id
- Update (Update): /widgets/update/:id
- Destroy (Delete): /widgets/destroy/:id
- New (precursor to create): /widgets/new
- Edit (precursor to update): /widgets/edit/:id
- List (lists all entities): /widgets/list
- Index (the default action): /widgets
When, you generate your scaffold, it’s going to automatically generate the 8 actions above. When designing entities if you have methods that don't fit within one of those actions then it's typically an indication that your entity model could our should be designed differently.
(A great example of how it's all about entity design is the login and logout actions for a User. I was thinking the other day about where the login and logout methods belong because they make sense on a User, but they aren't one of the above eight actions. Of course, I was thinking about it all wrong: login and logout are really the Create and Destroy methods on the Session entity, and Session entities belong to a User.)
Finally, a note in regard to the relationships between views, controllers and models in the context of validation. The typical user pattern in relation to creating an entity is:
- User visits /widgets/new page
- Enters data, click submit.
- /widgets/new POSTs to Widgets#create
- Widgets#create puts the data in the DB, then (if you look at the scaffold generated controller)
- If success, calls redirect_to
- If fails, calls render :action => :new
- If success, calls redirect_to
Why in one case does it redirect, and the other does it render? It all has to do with a little method call that should appear in your new widgets view, i.e. /widgets/new:
<%= error_messages_for 'widget' %>
See, a model has the capability to validate it’s attributes (e.g. lookup validates_presence_of in the Rails docs for examples of these capabilities). When you call Object#save the validation routines are executed and if the model doesn’t validate (i.e. Object#save returns false) we render the new action again. error_messages_for looks up the failures and automagically renders error messaging.
The beauty of generators is that script/generate scaffold Widget sets all of this up for you.
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
The Problem with Rails Plugins
The other day Mark asked if I was using active_scaffold. The answer is that I have a perfect use for it, and I installed it, and it works perfectly for what I need it for. However, it also overrides some core Rails functions, and when I execute functionality in my portion of the app the active_scaffold version of those functions are throwing exceptions. For example:class ActionController::Routing::RouteSet
def generate_with_nil_id_awareness(*args)
args[0].delete(:id) if args[0][:id].nil?
generate_without_nil_id_awareness(*args)
end
alias_method_chain :generate, :nil_id_awareness
end
Now, to me, ActionController::Routing::RouteSet seems like a pretty core function in Rails. Of course, it may be the case that I’ve done something wrong and their updated version is catching that error. (You can read more on that here: http://groups.google.com/group/activescaffold/browse_thread/thread/1c4e2f30e8b00ac6/309665c0a85d65c8).
However, my thinking is that I don’t need some plugin f’ing with my app. In fact, this points to a major issue with plugins…they’re not these self-contained units, i.e. components...but, rather, they are mixed in with the core Rails framework and our apps. This means we must think very carefully about which plugins we’ll use because, effectively, we need to know them as well as we know our own code. In other words, they are not black boxes...they are just code we import into our app that somebody else wrote (and is kind enough to share). For example, active_scaffold installs 138 files, and who knows how many kLOCs of code, and who knows what funky stuff they’ve done.
So, long story short, I’m not using active_scaffold because I don’t trust that there isn't come code in there that's gonna mess up my app, and it's too much code for me to review and become familiar with. Any ideas on an alternative?
I’ve looked at Streamlined, Hobo Scaffolding Extensions. According to the docs, Streamlined doesn’t do nested records editing which I require, Scaffolding Extensions handles nested record editing, but isn't the best UX, and Hobo has the same problem as Radiant CMS...I have to put my app into theirs, not their app into mine. (However, both Radiant and Hobo seem like nice platforms for the right project, just not the one I'm currently working on.)
4
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
What does "idiomatic Ruby" mean?
From a chat with Mark today, in regard to reading a post where I used the word "idiomatic":(10:10:42) Mark: idiomatic, what a word
(10:11:12) Scott Porad: yes, i don't even know what it means...but people
say it when they mean, "there's a more clever way to write this in ruby".
(10:11:26) Mark: Peculiar to or characteristic of a given language.
(10:12:05) Mark: nice, one of the descriptions of idiomatic, uses idiomatic
to describe it: Characterized by proficient use of idiomatic expressions
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Acts As Authenticated and Reset Password
Using Acts as Authenticated, imagine this use case:
- User forgets password...has reset code sent to their e-mail.
- User receives e-mail, clicks link to reset password.
- User arrives on reset password page and thinks, "hmmm...I think I'll go visit the homepage instead".
- User types http://www.yoursite.com/ in their browser (or clicks a link the header, or whatever).
What happens is that when the user clicks the link in the email it takes them to /account/reset_password which looks up their account by the reset code on the link (which was sent in the e-mail) and it logs them in. So, when they decide, "hmmm...I think I'll go visit the homepage instead," the user is now logged in, but has not reset their password.
To me, that seems to present a problem. So, I added a before_filter to my ApplicationController that verifies that all logged in users must have a nil password reset code otherwise they are redirected to /account/change_password. (The password reset code isn't cleared until after the user has successfully changed their password.)
In the ApplicationController I added:
before_filter :ensure_password_reset
andmodule AuthenticatedSystem
def ensure_password_reset
redirect_to :controller => :account, :action => :change_password unless reset_password_has_been_changed
end
def reset_password_has_been_changed
if logged_in?
if current_user.password_reset_code.nil?
return true
else
return false
end
else
true
end
end
end
I'm certain that there is a more idiomatic Ruby way to write reset_password_has_been_changed, but I couldn't think of it.
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Fixing a Blank Password Bug in Acts As Authenticated
I came across a bug in Acts As Authenticated when users tried to change their passwords. If they submitted the form with nothing in the new or confirm new password text field, then no error was thrown, but the password wasn't changed either.
The problem was in the :if clause on the validates_presence_of validation, password_required?. It was causing the validation not to occur. def password_required?
crypted_password.blank? || !password.blank?
end
This code is saying that a password is required in two situations:
- when the crypted_password is blank -- that situation happens when creating a new user, OR
- when the class instance variable 'password' is not blank -- this can only happen when the variable has been accessed, such as when attempting to update a password.
The bug is in the test for !password.blank? because it's assuming that the user will enter something as a new password. To resolve that, I changed the code to this:
def password_required?
crypted_password.blank? || !password.nil?
end
and now the validation is called (and fails) properly. More about this issue can be found in the last few posts on this page.
2
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
How To Make the Debugger Work with RadRails
I've finally got the debugger working with Aptana's RadRails.
I've had the debugger working for awhile, but I was experiencing a problem where the current line, i.e. the current execution line, wasn't being highlighted. Actually, the source file of the current line wasn't being even opened.
After trolling around various messages boards, etc., I learned that the bug has been fixed in the latest beta version of RadRails. Here’s a post on how to do that: http://www.aptana.com/forums/viewtopic.php?t=2939
Personally, I had to manually add the update site in order to get it to work, although you might not have that experience. Of course, it took me awhile to figure out how to do this...here you go:
- Go to Help > Software Updates > Find and Install
- Select "Search for new features to install" and click "Next"
- Click the button on the right for "New Remote Site"
- Enter:
- Name: RadRails Beta
- URL: http://update.aptana.com/update/rails/beta/3.2/site.xml
- Click 'OK'
- Check the box next to "RadRails Beta"
- Click the "Finish" button.
Now the update should download and install.
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Where to put/store/save/keep your modules and files containing modules?
To a Rails newbie, sometimes the simplest things are hard to figure out. Here's what you need to know:
When you create a module, you save it to your lib/ directory.
All the modules in the lib/ directory are auto-loaded by Rails. That is, Rails does something like this:
for file in lib/
require file
end
Also, I think there is some magic to this, but I'm not 100% sure. If you have a module called MiscUtils then your file needs to be named misc_utils.rb in order for Rails to auto-load it.Additionally, Ruby does this super-sweet thing where you can re-open any class or module and add to it at any time. In other words, you can declare a class or module in two locations, and Ruby will merge them together and treat them as one class. My experience has been that when you do this, then you need to explicitly require the files even if they're in the lib directory.
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
What is that hyphen right before the closing of an ERb block?
Periodically, I see some ERb code in a view like this:
<% form_tag '/posts' do -%>
<%= submit_tag 'Save' %>
<% end -%>
In fact, that code was culled right from the Rails docs at for form_tag
As you can see, in those two ERb tags, there is this syntax at close of the tag:
-%>Today I was wondering what the hyphen (-) was for before the percentage symbol (%). It turns out that the hyphen means that when the HTML output is generated there is no line return after the close of the ERb tag.
For example, the ERb code above produces this HTML:
<form action="/posts" method="post"> <div><input name="commit" type="submit" value="Save" /></div>
</form>
whereas this ERb code:
<% form_tag '/posts' do %>
<%= submit_tag 'Save' %>
<% end %>
produces this HTML:
<form action="/posts" method="post">
<div><input name="commit" type="submit" value="Save" /></div>
</form>
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
How Mixins, Include and Extend Work
I was a little puzzled tonight by this chunk of code that I found in the acts_as_authenticated plug-in module: def self.included(base)
base.send :helper_method, :current_user, :logged_in?
end
It comes down to some Ruby magic: when a module is included by a class the self.included method on the module is called. Likewise, when a class extends a module the self.extended method is called.
"base" is the class that includes/extends the module. "send" is calling the method ":helper_method" and passing ":current_user" and ":logged_in?" as parameters.
Special thanks to Juixe for an excellent article that helped me figure this out.
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
DRY Migrations (aka reverting or undoing earlier migrations)
I have a case where I made some database changes in migration 001 and now I want to undo them in migration 005. This is different that actually rolling back to version 001 (i.e. rake db:migrate version=1)...I actually want to undo or revert what I did in 001. The obvious thing to do would be to simply have 005 do the opposite of 001, but that isn't very DRY.
Using a simple example, let's say my migrations were:
- 001_create_books.rb
- 002_create_libraries.rb
- 003_create_librarians.rb
and now my library is going electronic, so I do this:
- 004_create_e_books.rb
- 005_destroy_books.rb
In 005 I want to do the exact opposite of 001, so I did this:
class DestroyBooks < ActiveRecord::Migration
def self.up
CreateBooks::migrate(:down)
end
def self.down
CreateBooks::migrate(:up)
end
end
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Custom Configurations and App Specific Settings
One not immediately obvious Ruby on Rails configuration issue I came across is how to structure application-specific config parameters, and in particular, how to make them configurable/overridable across different environments (dev, test, production). This has been solved repeatedly in different ways by the Rails community and there's info scattered around but assimilating it took a while, here's what I've settled on for now.
I couldn't have said it better myself. I've now spent 4 hours researching the best way to do this...this is a basic feature of a web app, you'd think there would be a conventional way to create ..whatever you want to call them: custom configurations, application specific settings, application configs...in Rails.
At present, I've found four solutions...the one suggested by the above blogger, and these three others:
- http://www.taknado.com/2007/7/25/custom-configuration-info-in-rails
- http://jarmark.org/projects/app-config/
- Use after_initialize method on the Rails::Configuration class. (Note: this is only semi-well documented...it's documented, but not included at http://api.rubyonrails.org. I found it here: http://edgedocs.planetargon.org/classes/Rails/Configuration.html#M002860)
In addition, I found these blog posts useful:
- http://toolmantim.com/article/2006/12/27/environments_and_the_rails_initialisation_process
- http://glu.ttono.us/articles/2006/05/22/guide-environments-in-rails-1-1
I haven't decided how I'm going to do this yet, but I hope you find this helpful.
UPDATE: I was exchanging e-mail from Jeff at softiesonrails.com who suggested this solution:
What I usually do is add it to the bottom of environment.rb. If I have RAILS_ENV-dependent data (like development mode vs. production mode), then just put the relevant Ruby code at the bottom of environments/development.rb, for example:module MyConstants
ALLOWED_NAMES = ['jeff', 'cookie monster']
IP_ALLOWED = '1.2.3.4'
end
and then you can access them anywhere in your Rails code as MyConstants::ALLOWED_NAMES, etc.
If you prefer to move it to a file, you'd create a file named my_constants.rb in the /lib folder, and then explicitly require it from environment.rb:require 'my_constants'
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Reverting Migrations (self.drop) Issue
I created an ran a migration today. Here is how my database looked to begin:
mysql> show tables;
+--------------------------------------+
| Tables_in_books_development |
+--------------------------------------+
| journals |
| schema_info |
+--------------------------------------+
2 rows in set (0.00 sec)
mysql> select * from schema_info;
+---------+
| version |
+---------+
| 19 |
+---------+
1 row in set (0.00 sec)
Then, I ran this migration:
class CreateThemes < ActiveRecord::Migration
def self.up
create_table :themes do |t|
t.column :name, :string
t.column :stylesheet_path, :string
t.column :thumbnail_path, :string
t.column :journals_count, :integer, :default => 0
end
#add_column :journals, :theme_id, :integer
end
def self.down
drop_table :themes
remove_column :journals, :theme_id
end
end
Notice how I have the add_column method commented out. Running Rake yields this:
C:\rails_apps\books>rake db:migrate
(in C:/rails_apps/books)
== CreateThemes: migrating ====================================================
-- create_table(:themes)
-> 0.1200s
== CreateThemes: migrated (0.1200s) ===========================================
As you can see, the column is not added to the journals table. Here's what my database looks like now:
mysql> show tables;
+--------------------------------------+
| Tables_in_books_development |
+--------------------------------------+
| journals |
| schema_info |
| themes |
+--------------------------------------+
3 rows in set (0.00 sec)
mysql> select * from schema_info;
+---------+
| version |
+---------+
| 20 |
+---------+
1 row in set (0.00 sec)
Well, I really need that column added to journals, so I better revert that migration via Rake, uncomment the add_column method, and re-Rake. Here's what happens:
C:\rails_apps\books>rake db:migrate version=19
(in C:/rails_apps/books)
== CreateThemes: reverting ====================================================
-- drop_table(:themes)
-> 0.0500s
-- remove_column(:journals, :theme_id)
rake aborted!
Mysql::Error: Can't DROP 'theme_id'; check that column/key exists: ALTER TABLE journals DROP `theme_id`
(See full trace by running task with --trace)
Oops! The self.down method is crapping out because there is no column in journals called theme_id. (Of course, we knew that.) Let's checkout the database now:
mysql> show tables;
+--------------------------------------+
| Tables_in_books_development |
+--------------------------------------+
| journals |
| schema_info |
+--------------------------------------+
2 rows in set (0.01 sec)
mysql> select * from schema_info;
+---------+
| version |
+---------+
| 20 |
+---------+
1 row in set (0.00 sec)
Do you see that schema_info still says version 20. I presume that the last thing a migration does is update the schema_info.version with the idea being that we don't modify the version until we sure that the migration has succeeded. The problem with that is that migrations aren't transactional--that is, they can complete or fail partially, yet the schema_info is updated as though it were a transaction. I don't know how Rails fixes this, but it's something worth knowing about.
Anyhow, at this point my database is in limbo...neither in version 19 nor 20. When I run
rake db:migratenothing happens because as far as Rake can tell, the DB is up-to-date. But, I can't run
rake db:migrate version=19either because Rake will error out because there is no theme table to drop.
Okay, so the short-term solution to this problem is to clean-up the database manually. In my case, everything was actually reverted in the self.drop, but Rake doesn't know that. In your case you may have more manual clean-up to do. So, all I needed to do was update schema_info.version to 19.
1 comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Netscape Navigator 1.0
I'm not getting much work done today...my desk and office are a mess, so I'm working at cleaning up.
While doing so, I found a bit of history in my desk, and you can have it.
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Create Action Requires POST
UPDATE: I wrote the whole post below, and then I figured it out...oy, the risks of auto-generated code. Typically, I use script/generate scaffold to build my controllers and views, then I start modifying from there. The risk of using auto-generated code is that you don't know every detail...and, if you're gonna own a program, you gotta know ever detail.
Long story short: I started digging around at .../verification.rb and I finally ended up back at my own controller and found this that scaffold sticks this bit of code in at the top of every controller:
# GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
verify :method => :post, :only => [ :destroy, :create, :update ],
:redirect_to => { :action => :list }
which is why I wasn't able call create with a GET. Yikes!
Boy, what a morning! I found a "feature" of Rails that I don't quite understand yet, but it certainly caused me a lot of headache. Maybe somebody else who is frustrated will benefit from this information.
Long story short: if you are going to call the create action in a controller, then you can only do so via POST. If you try to do so via GET you will get an error like the one below. In other words:
<html>
<body>
Form with POST method --> works
<form action="/books/create" method="post">
<input type="submit" name="submit" value="submit">
</form>
Form with GET method --> does not work
<form action="/books/create" method="get">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Apparently, Rails has some sort of before_filter that requires certain types of actions to be called via certain HTTP methods. (Note: I am not using any of the Rails RESTful stuff, e.g. map.resources.)
I have yet to figure out exactly what filter causes this requirement. Also, I would be interested in knowing if there is a way to inspect all the before filters that will be run for a given action or controller. If you know, please post in the comments.
Special thanks to Dirkjan for helping me debug this far.
From development.log
Processing BooksController#create (for 127.0.0.1 at 2007-09-11 10:53:22) [GET]
Session ID: e042ea5ba771fd5423d39369ec8e1227
Parameters: {"action"=>"create", "controller"=>"books", "journal_id"=>"1"}
Redirected to http://localhost:3005/books/list
Filter chain halted as [#<ActionController::Filters::ClassMethods::ProcFilter:0x47e198c @filter=#<Proc:0x0391ce4c@C:/InstantRails-1.7-win/InstantRails/ruby/lib/ruby/gems/1.8/gems/actionpack-1.13.3/lib/action_controller/verification.rb:74>>] returned false.
Completed in 0.01000 (100 reqs/sec) | DB: 0.00000 (0%) | 302 Found [http://localhost/books/create?journal_id=1]
Processing BooksController#list (for 127.0.0.1 at 2007-09-11 10:53:22) [GET]
Session ID: e042ea5ba771fd5423d39369ec8e1227
Parameters: {"action"=>"list", "controller"=>"books"}
[4;36;1mBook Columns (0.010000)[0m [0;1mSHOW FIELDS FROM books[0m
[4;35;1mSQL (0.000000)[0m [0mSELECT count(*) AS count_all FROM books [0m
[4;36;1mBook Load (0.000000)[0m [0;1mSELECT * FROM books LIMIT 0, 10[0m
Rendering within layouts/books
Rendering books/list
Completed in 0.03000 (33 reqs/sec) | Rendering: 0.01000 (33%) | DB: 0.01000 (33%) | 200 OK [http://localhost/books/list]
0
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
How to use IRC for Ruby on Rails (#rubyonrails)
14 years ago I used IRC to chat with people online about the Grateful Dead and Phish, but haven't since, and basically forgot about 99% of how it works.
Then, recently I wanted to join the #rubyonrails IRC channel to get some instant information, so from http://www.rubyonrails.com/community I learned that #rubyonrails was hosted at irc.freenode.net. I downloaded ChatZilla and tried to join.
Frustration. #rubyonrails requires some sort of nickname registration and it took me the longest time to figure out how the heck it works.
I searched for documentation and found all sorts, but what I was found was very dry and technical and full of details. Typically, I like that type of stuff--bare bones, just the facts.
But, here I needed the dummies course, and I found it at http://www.zymic.com/irc.php. I can't vouch for that site, but thank goodness they had some basic info...it wasn't 100% correct, but it got me close enough.
In ChatZilla > Preferences > General there is a "nickname" setting. When you connect to irc.freenode.net you need to register this nickname...obviously, it should be something sort of unique. (How to connect? Open Firefox and visit the URL irc://irc.freenode.net ...which should launch ChatZilla.)
After ChatZilla connects to irc.freenode.net, you will need to register your nickname, aka "nick". To register the nick, type:/msg nickserv register <yourpassword>
where <yourpassword> is some password of your creation. This will register your nickname with some sort of central registration database.
Then, to enter the channel type:/join #rubyonrails
On subsequent visits to IRC, ChatZilla will send your username to nickserv, but you will need to "identify" yourself this time. To do so, type:/msg nickserv identify <yourpassword>
Then, join the channel like you did before:/join #rubyonrails
Personally, I think of it like this:
- register = create a login
- identify = login
- join = enter a chat room
Hopefully, these instructions will help someone else out along the way.
P.S. By the way, the delay between posts is explained by the fact that I was out of town for a few weeks visiting family.
2
comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot
Incorporation
We incorporated our startup today...a small milestone on a long journey, so we took a picture to commemorate the moment.
1 comments
Share This Post On: del.icio.us |
Digg |
Reddit |
Slashdot