this makes me want to try to hack rails sites... :-P just kidding. though it would be really cool if i could hack someone's site who i know, i'd get lots of cred for that! but honestly this was really cool because i think there's a lack of stuff addressing security concerns in rails, i've kind of wondered about things like this before but never really seen it explained... thanks
The naming confuses me. The session gets created automatically somehow by rails when a browser accepts a cookie or something? If you navigate to "new" I guess you get given a form text field that will call the create action that doesnt create a new session but sets the session[:password] . Is "create" a misnomer or am I missing something? Shouldn't it be called something like "set_password". The destroy seems to actually destroy all session information, not just the password so the naming seems appropriate.
I guess the virtual object setters get called when Rails trys to create a new object in the controller using the full_name attribute. It happens after it hits the controller, not before it (or maybe during the controller create action is a better way of thinking about it).
Intersting that you didn't show the controller at all. I guess when you use form_for the parameters are automatically associated with the model object, not just named after the model object?
If so, why would the controller still do something like @user.update_attributes(:parmams) ? (or do you avoid that step somehow?)
Does the virtual attribute change the params? I'm confused about how this is working.
I've been enjoying all your screencasts and learning incrementally from each...not only on the given subjects but getting some clue to context, procedure, and conventions.
I am completely new to programming, read a ruby book 6 months ago or so, and read the agile rails books and a few others(I had read some html stuff a couple years ago).
I must echo Sydney's comments that there is a big hole out there in the literature in terms of giving absolute newbies to computing the knowledge to finish and deploy rails projects following good conventions.
Not saying that is your job but it would be nice for someone to write a bigger primer on all the stuff circulating outside of the code and assuming that someone will be writing an application on a home computer they previously only wrote Word files on (and perhaps computer games), and browsed the internet on...and plan to host their application externally and a rails hosting provider.
While learning subversion seems necessary at some point a whole new learning curve and the need to work with all that command line stuff just to get to you documents is bit of a hurdle and a drain. And I guess I'm going to need to learn capistrano and a few other things.
Step by step inch by inch I'll get closer and so many people like you are sharing so generously on topics that there are resources available here and there. I'd like a few more showing how you actually work and where programs are kept.
Do I understand that I create a subversion directory where I eventually will host the application and check out files to work on from there and bring them to my home computer? Will the working production copy be a checked out copy or will it be running from the subversion directory?
(ok, I guess those questions show how cluesless I still am about systems stuff)
this is another great screen cast. My problem is, that i want to achieve exactly what you show here, including model based validation. Any possibility to achieve that "the rails way"?
I'm having a little problem with the "project[task_attributes][]" part. I've watched the screencast on virtual attributes, I have "def task_attributes=(attributes)" in my model, but I get the message "`@project[task_attributes]' is not allowed as an instance variable name". It works fine when I have "project[task_attributes]" in my form without the extra brackets, but I want to be able to support an array. What am I missing here?
@NoobSaibot, I hope to cover custom form builders in a future episode. Thanks for the suggestion!
@Mr Bogus, I haven't done any performance testing on this yet so I'm not really sure of the overhead.
@Mike, if you already have a working solution that doesn't cause problems or constant maintenance then I would say stick with it. The biggest benefit I see to a cookie based store is the zero maintenance.
I am using SQLSessionStore plugin (wich was proven to be far more faster the the default file method and even the activercrd session method). Is it smart to switch over to the new cookie method?
Hallison,
I am having the same experience of the missing all_helper.rb with a reinstall on a shared server. If you find out the cause of your error would you be kind enough to post it here? The host has not been able to help and I am going nuts.
My rails version is 1.2.3
Thank you
If you are using secret ID numbers, you should really evaluate why you are doing this. Is there harm in letting the user see that an object is number 1001, and is that different than seeing an encrypted id of 10230103103, if both are constants?
Here is a little fix for keeping the generated checkbox code standards complain :
<%= check_box_tag "product[category_ids][]",category.id, @product.categories.include?(category),{ :id => "product_category_ids_"+ category.id.to_s} %>
The example from Ryan puts "[]" into the id field of the input tag and this is not allowed according to the w3 ;)
If one of your goals is to use obfuscated URLs to hide the IDs of users and other objects, doesn't storing the ID of the user in the cookie screw things up for you? I guess unless you store the encrypted ID...
You didn't mention this, but I assume the encrypted cookie approach also has an added overhead of session data encryption and decryption. Perhaps a good use for memcached.
I remember when it was impossible for me to open or even delete the sessions folder on my server because it was filled with thousands of files. Ended up using some shell command that I can't recall, and even then it took a few minutes to complete.
I know people aren't crazy about MS's View State, but is there a way in Rails to write session state to the rendered html. I have users that do not want to use cookies.
Neeraj: It's actually been changed to rake secret. I originally had it as that long winded rake task but after talking to bitsweat and DHH, it got shorten down to rake secret.
If you are migrating from Rails 1.2 then you can use this rake task to generate the secret key.
rake secret:generate:key More info at
http://dev.rubyonrails.org/ticket/10363
Wouldn't it be nice to include the approved filter in the relationship between the Post and the Comment. Like this:
has_many( :comments, :class_name => "Comment", :conditions => {:approved => true}, :dependent => :destroy )
Then the simplify the finding in the controller as the condition would be built into the association so a simple find(:all) would suffice. Just my $0.02. Anyway a great screencast and keep up the good work.
So, ignore step 1 (it was referring to the iq_noscript_friendly plugin) and just follow steps 2 and 3, using the Rails link_to helper as normal (with a :href argument pointing to the delete action).
1. Remove the plugin (I don't believe a version for Rails 2 exists). Rails will now write the confirmation javascript to send a DELETE to the link's href - i.e. to the delete action.
2. Change your routes.rb so that the delete action accepts DELETE as well as GET. E.g.
I've created some 'foxy fixtures' but when I try to load them into my development database using "rake db:fixtures:load" I get SQL errors because the _id suffix doesn't seem to be added to the foreign key columns like I would expect it to be. Has anyone else noticed this when using rake db:fixtures:load?
This has to be my favourite till now!
Thank you so much i really didn't know how to accomplish that (it is my first rails (and web development in general) project!)
I am having a problem with the "this.up" method in Internet Explorer. Any time it is called, there is a "object doesn't support this property or method".
Tried searching Google but it seems impossible to search for "this.up" since it instead searches for "this up".
@Valerie:
1. Install by gems (not from source) - it should be a command line tools but in netbeans/eclipse plugins you have GUI
2. 'application/pdf' is mime type
Just wanted to point out that script/console production --sandbox can be dangerous. Any models objects you load up that way will lock the database for those rows (assuming your db's transactions use a certain form of lock), effectively stopping your site from running. Use with care!
I'm currently using restful_authentication. So, in the move to Rails 2.0, should I stick with that and "enhance" it with this? Based on August's comments, that is what is implied. Where might the code August posted be put? Sorry, my newby-ness is apparent.
If someone is interested, tnx to dr. google and Rich's code at http://www.justatheory.com/computers/databases/postgresql/rails_and_slony.html, here's my rake task that scripts migration into migration.sql file. Place the code in lib/tasks/whatever.rake and than call rake db:script_migration. However, this scrips all migrations from 0.
namespace :db do
desc "Script SQL from migration"
task :script_migration => :environment do
ActiveRecord::Base.connection.class.class_eval do
# alias the adapter's execute for later use
alias :old_execute :execute
# define our own execute
def execute(sql, name = nil)
# check for some DDL and DML statements
if /^(create|alter|drop|insert|delete|update)/i.match sql
File.open('migration.sql', 'a') { |f| f.puts "#{sql}\n" }
else
# pass everything else to the aliased execute
old_execute sql, name
end
end
end
# create or delete content of migration.sql
File.open('migration.sql', 'w') { |f| f.puts "-- Script created @ #{Time.now}" }
# invoke the normal migration procedure now
Rake::Task["db:migrate"].invoke
end
end
@Ryan, Yes, I ment exactly that. It is very useful if your DB admin's don't allow DDL as it is case in my bank. So procedure is to give them script, they check it and then they execute it. I have to find the way to make such a rake task.
I would like to implement a PDF function into my application.
I have already installed the pdf-writer-1.1.6.
Firstly, there are several folders in this zip folder e.g. pdf, writer etc.
Where exactly should I paste this folders to?
Secondly, I added the following codes to the environment.rb:
require 'pdf/writer'
Mime:Type.register 'application/pdf',:pdf
Where should I place these codes and the should the word "application" be replaced with my project's name?
I am sure that there is something wrong with the codes in here as when i restarted WEBRICK in my command prompt, some of the errors that occurred are:
- already initialized constant OPTIONS
-no such file to load -- transaction/simple<MissingSourceFile>
Can someone please give me a solution? Because there is no way I can implement the codes if I cannot start my WEBrick successfully.
This is quite urgent as the deadline is drawing nearer. Please help!
Thank you very much!!!
@Ryan, I don't see what benefit storing it in a session would give because the browser will usually store the login credentials on its own. If you store it in a session it will be in two different places which could get messy.
As for HTTP Digest Authentication, I don't think Rails 2.0 offers an easy way to do this. But I haven't looked into it.
Also, I don't see any way to incorporate OpenID authentication into this.
@nicolash, good point. I think pluralizing it makes sense.
@DAddYE, yep! I did receive the email, but I haven't had time to respond to it yet. Things have been busy here.
@burmaja, do you mean a way to convert a migration to SQL? I don't know of a rake task that does this, but there's probably some way to write one. Haven't looked into it.
Do you know if its possible to use http to request information from the user other than login credentials?
this makes me want to try to hack rails sites... :-P just kidding. though it would be really cool if i could hack someone's site who i know, i'd get lots of cred for that! but honestly this was really cool because i think there's a lack of stuff addressing security concerns in rails, i've kind of wondered about things like this before but never really seen it explained... thanks
I came up with a solution for checkboxes based on Ryan's suggestion of using javascript.
application helper
http://pastie.caboo.se/131145
application javascript
http://pastie.caboo.se/131144
I also see URL-escaped characters on child nodes. Problem is I can't unescape them. They stay escaped for some reason. :/
rails 2.0.1
The naming confuses me. The session gets created automatically somehow by rails when a browser accepts a cookie or something? If you navigate to "new" I guess you get given a form text field that will call the create action that doesnt create a new session but sets the session[:password] . Is "create" a misnomer or am I missing something? Shouldn't it be called something like "set_password". The destroy seems to actually destroy all session information, not just the password so the naming seems appropriate.
doh, I think I got it.
I guess the virtual object setters get called when Rails trys to create a new object in the controller using the full_name attribute. It happens after it hits the controller, not before it (or maybe during the controller create action is a better way of thinking about it).
Intersting that you didn't show the controller at all. I guess when you use form_for the parameters are automatically associated with the model object, not just named after the model object?
If so, why would the controller still do something like @user.update_attributes(:parmams) ? (or do you avoid that step somehow?)
Does the virtual attribute change the params? I'm confused about how this is working.
I've been enjoying all your screencasts and learning incrementally from each...not only on the given subjects but getting some clue to context, procedure, and conventions.
I am completely new to programming, read a ruby book 6 months ago or so, and read the agile rails books and a few others(I had read some html stuff a couple years ago).
I must echo Sydney's comments that there is a big hole out there in the literature in terms of giving absolute newbies to computing the knowledge to finish and deploy rails projects following good conventions.
Not saying that is your job but it would be nice for someone to write a bigger primer on all the stuff circulating outside of the code and assuming that someone will be writing an application on a home computer they previously only wrote Word files on (and perhaps computer games), and browsed the internet on...and plan to host their application externally and a rails hosting provider.
While learning subversion seems necessary at some point a whole new learning curve and the need to work with all that command line stuff just to get to you documents is bit of a hurdle and a drain. And I guess I'm going to need to learn capistrano and a few other things.
Step by step inch by inch I'll get closer and so many people like you are sharing so generously on topics that there are resources available here and there. I'd like a few more showing how you actually work and where programs are kept.
Do I understand that I create a subversion directory where I eventually will host the application and check out files to work on from there and bring them to my home computer? Will the working production copy be a checked out copy or will it be running from the subversion directory?
(ok, I guess those questions show how cluesless I still am about systems stuff)
Would you pl help me to fix this,in my old rails version i used to render files like
render(:partial=>'list_categories')
Now its not working with version 2.0.2.How can i make it work???
Thanks in advance
hi, i am using pdf:writer with attachment_fu and when i am trying to load an image into the pdf like so.
avatar = @villa.avatar.public_filename()
pdf = PDF::Writer.new(:paper => "A4")
pdf.select_font "Helvetica"
pdf.image avatar, :resize => 0.75
but all i get is an error.
"No such file or directory - /avatars/0000/0007/1.jpg"
so whats wrong here?
thx for the great screencast :)
Ryan,
this is another great screen cast. My problem is, that i want to achieve exactly what you show here, including model based validation. Any possibility to achieve that "the rails way"?
I'm having a little problem with the "project[task_attributes][]" part. I've watched the screencast on virtual attributes, I have "def task_attributes=(attributes)" in my model, but I get the message "`@project[task_attributes]' is not allowed as an instance variable name". It works fine when I have "project[task_attributes]" in my form without the extra brackets, but I want to be able to support an array. What am I missing here?
@NoobSaibot, I hope to cover custom form builders in a future episode. Thanks for the suggestion!
@Mr Bogus, I haven't done any performance testing on this yet so I'm not really sure of the overhead.
@Mike, if you already have a working solution that doesn't cause problems or constant maintenance then I would say stick with it. The biggest benefit I see to a cookie based store is the zero maintenance.
I am using SQLSessionStore plugin (wich was proven to be far more faster the the default file method and even the activercrd session method). Is it smart to switch over to the new cookie method?
Hallison,
I am having the same experience of the missing all_helper.rb with a reinstall on a shared server. If you find out the cause of your error would you be kind enough to post it here? The host has not been able to help and I am going nuts.
My rails version is 1.2.3
Thank you
If you are using secret ID numbers, you should really evaluate why you are doing this. Is there harm in letting the user see that an object is number 1001, and is that different than seeing an encrypted id of 10230103103, if both are constants?
going to try this in rails 2.0 right now, i will let you know how it goes. great screencasts ryan they have been helping me out alot!
Best,
Here is a little fix for keeping the generated checkbox code standards complain :
<%= check_box_tag "product[category_ids][]",category.id, @product.categories.include?(category),{ :id => "product_category_ids_"+ category.id.to_s} %>
The example from Ryan puts "[]" into the id field of the input tag and this is not allowed according to the w3 ;)
If one of your goals is to use obfuscated URLs to hide the IDs of users and other objects, doesn't storing the ID of the user in the cookie screw things up for you? I guess unless you store the encrypted ID...
You didn't mention this, but I assume the encrypted cookie approach also has an added overhead of session data encryption and decryption. Perhaps a good use for memcached.
Thanks! Error occurred...
undefined method `formatted_programmes_path'
Seriously, I don't see where i should define this.
When I do this I get a 'undefined method "article_path"' error from my partial. It doesn't like "article" in my link_to.
I didn't know Rails 2.0 had this.
I remember when it was impossible for me to open or even delete the sessions folder on my server because it was filled with thousands of files. Ended up using some shell command that I can't recall, and even then it took a few minutes to complete.
I know people aren't crazy about MS's View State, but is there a way in Rails to write session state to the rendered html. I have users that do not want to use cookies.
@Ryan, have you found a permanent solution to creating the record instead of save(false)?
Neeraj: It's actually been changed to rake secret. I originally had it as that long winded rake task but after talking to bitsweat and DHH, it got shorten down to rake secret.
i wonder why it is not possible to create a submit button by writing something like: f.submit
This makes it kinda difficult to create custom form builder.
Do you have any hints on that issue?
If you are migrating from Rails 1.2 then you can use this rake task to generate the secret key.
rake secret:generate:key More info at
http://dev.rubyonrails.org/ticket/10363
you could also store the model in memcached using cache_fu. (no DB hit)
Class User
acts_as_cached
after_save expire_cache
end
User.get_cache(id)
User.reset_cache(id)
the only problem is shared hosts won't have memcached availability.
here I have some examples
http://www.frederico-araujo.com/2007/12/13/make-your-rails-app-faster-with-memcached-part-1
I know Ryan is gonna come up with a memcached/cache_fu screencast sometime...
All screencasts here are awesome.
What a great job!
Thanks a lot Ryan!!!
Wouldn't it be nice to include the approved filter in the relationship between the Post and the Comment. Like this:
has_many( :comments, :class_name => "Comment", :conditions => {:approved => true}, :dependent => :destroy )
Then the simplify the finding in the controller as the condition would be built into the association so a simple find(:all) would suffice. Just my $0.02. Anyway a great screencast and keep up the good work.
:-D
That was meant for a different site.
So, ignore step 1 (it was referring to the iq_noscript_friendly plugin) and just follow steps 2 and 3, using the Rails link_to helper as normal (with a :href argument pointing to the delete action).
One potential solution is the following:
1. Remove the plugin (I don't believe a version for Rails 2 exists). Rails will now write the confirmation javascript to send a DELETE to the link's href - i.e. to the delete action.
2. Change your routes.rb so that the delete action accepts DELETE as well as GET. E.g.
map.resources :sites, :member => { :delete => :get, :delete => :delete }
3. Change your delete action to call destroy if the request is a DELETE, or render the delete confirmation form if not.
def delete
destroy if request.delete?
// Otherwise renders delete.rhtml
end
I've created some 'foxy fixtures' but when I try to load them into my development database using "rake db:fixtures:load" I get SQL errors because the _id suffix doesn't seem to be added to the foreign key columns like I would expect it to be. Has anyone else noticed this when using rake db:fixtures:load?
Thanks for making these. I like how you are focusing on features of Rails 2.0. Please continue this theme.
Seeing the new features and changes in action is very helpful and useful for me, especially since all the books cover mostly Rails 1.2.5.
This has to be my favourite till now!
Thank you so much i really didn't know how to accomplish that (it is my first rails (and web development in general) project!)
I am having a problem with the "this.up" method in Internet Explorer. Any time it is called, there is a "object doesn't support this property or method".
Tried searching Google but it seems impossible to search for "this.up" since it instead searches for "this up".
Any help would be appreciated
Hi Ryan,
Could you please explain what is projects_path?
It is not very clear for me.
Yours,
@Valerie:
1. Install by gems (not from source) - it should be a command line tools but in netbeans/eclipse plugins you have GUI
2. 'application/pdf' is mime type
hi,
if i override the to_param in user model, I will get more meaningful urls in
localhots:3000/users/peter_permalink/tests
instead of
localhots:3000/users/2/tests
however, that makes my restful_authentication plugin not work so well.
is there a way out?
thanks
It works. But does this work with paginate plugin as well?
I upgraded to rails 2
using this command
gem install rails -y --source http://gems.rubyonrails.org
when I try to strip away all the 'id:' from my fixtures, test case failed. It complains that id cannot be found.
does anyone know what might possibly went wrong?
Hey,
Just wanted to point out that script/console production --sandbox can be dangerous. Any models objects you load up that way will lock the database for those rows (assuming your db's transactions use a certain form of lock), effectively stopping your site from running. Use with care!
I'm currently using restful_authentication. So, in the move to Rails 2.0, should I stick with that and "enhance" it with this? Based on August's comments, that is what is implied. Where might the code August posted be put? Sorry, my newby-ness is apparent.
If someone is interested, tnx to dr. google and Rich's code at http://www.justatheory.com/computers/databases/postgresql/rails_and_slony.html, here's my rake task that scripts migration into migration.sql file. Place the code in lib/tasks/whatever.rake and than call rake db:script_migration. However, this scrips all migrations from 0.
namespace :db do
desc "Script SQL from migration"
task :script_migration => :environment do
ActiveRecord::Base.connection.class.class_eval do
# alias the adapter's execute for later use
alias :old_execute :execute
# define our own execute
def execute(sql, name = nil)
# check for some DDL and DML statements
if /^(create|alter|drop|insert|delete|update)/i.match sql
File.open('migration.sql', 'a') { |f| f.puts "#{sql}\n" }
else
# pass everything else to the aliased execute
old_execute sql, name
end
end
end
# create or delete content of migration.sql
File.open('migration.sql', 'w') { |f| f.puts "-- Script created @ #{Time.now}" }
# invoke the normal migration procedure now
Rake::Task["db:migrate"].invoke
end
end
@Ryan, Yes, I ment exactly that. It is very useful if your DB admin's don't allow DDL as it is case in my bank. So procedure is to give them script, they check it and then they execute it. I have to find the way to make such a rake task.
Hi,
I would like to implement a PDF function into my application.
I have already installed the pdf-writer-1.1.6.
Firstly, there are several folders in this zip folder e.g. pdf, writer etc.
Where exactly should I paste this folders to?
Secondly, I added the following codes to the environment.rb:
require 'pdf/writer'
Mime:Type.register 'application/pdf',:pdf
Where should I place these codes and the should the word "application" be replaced with my project's name?
I am sure that there is something wrong with the codes in here as when i restarted WEBRICK in my command prompt, some of the errors that occurred are:
- already initialized constant OPTIONS
-no such file to load -- transaction/simple<MissingSourceFile>
Can someone please give me a solution? Because there is no way I can implement the codes if I cannot start my WEBrick successfully.
This is quite urgent as the deadline is drawing nearer. Please help!
Thank you very much!!!
hi ryan,
i was just wondering if you have idea where i can get a dummy's guide for different levels of authorisation.
like some people will be able to CRUD,
some write only, some read only.
i'm very new to RoR sadly
thanks in advance!
Hey,
You can also use references eg,
t.references :post, :user
and it will create integer foreign keys
post_id
user_id
Cheers
@Ryan, I don't see what benefit storing it in a session would give because the browser will usually store the login credentials on its own. If you store it in a session it will be in two different places which could get messy.
As for HTTP Digest Authentication, I don't think Rails 2.0 offers an easy way to do this. But I haven't looked into it.
Also, I don't see any way to incorporate OpenID authentication into this.
@nicolash, good point. I think pluralizing it makes sense.
@DAddYE, yep! I did receive the email, but I haven't had time to respond to it yet. Things have been busy here.
@burmaja, do you mean a way to convert a migration to SQL? I don't know of a rake task that does this, but there's probably some way to write one. Haven't looked into it.