No Comments »

While it is always good to have attr_accessible or attr_protected set in a ActiveRecord model class to protect it from abuse when updating any object of that class from the params of a Rails controller.

But what to do when you have that attr_accessible but you won’t let a certain action in your controller even edit all of those accessible fields. Maybe because you’re paranoid or just a think that an action should only be allowed to edit what they was invented for, there might be some good reasons.

We faced this problem lately and came up with that solution:

1
2
3
4
5
6
7
8
9
10
11
12
class ActiveRecord::Base
  def update_by_params(params, *fields)
    self.attributes = params.reject
        {|key,value| !fields.index key.to_sym}
    self.save
  end
  def update_by_params!(params, *fields)
    self.attributes = params.reject
        {|key,value| !fields.index key.to_sym}
    self.save!
  end
end

The update_by_params instance method on the ActiveRecord::Base class let you do something like this:

1
2
3
4
5
6
# ... in a controller ...
def change_password
  @current_user.update_by_params(params[:user],
      :password, :password_confirmation)
  redirect_to frontpage_url
end

And then the user won’t be able to edit his address with a hacked password change form, even if he is allowed to do so in his profile.

The method will save the object after the update. To handle errors on saving there are (as usual in Rails) two specifications of this method available, one with a ! at the end which just uses save! to save the object and one without the ! which uses save. So update_by_params! will throw an error if the save fails while update_by_params just returns false.

Have fun with that.

Yours,

Thorben
FEtMab-Team

No Comments »

Rails 2.0 will ship with a new ActionController class method called:

1
rescue_from Exception, :with => :method_name

…which will rescue all exceptions in actions, thrown when the application runs in production mode with the given method.

As I read that I thought: Why only in production mode? It seems the Rails team designed this tool to rescue exceptions that were not wanted to be thrown, but why?

In our newest application I had the problem that we wanted to be able to display e.g. a login box on several places all over the app.
We created a login box partial which displayed a form that posted the login to the login action at the user controller. But what if the login fails? We ended up with something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def login
  unless request.post?
    flash[:notice] = :login_failed
    redirect_to_last_page
    return
  end
  user = User.authenticate(params[:nickname], params[:password])
  unless user
    flash[:notice] = :login_failed
    redirect_to_last_page
    return
  end
  #doing the login stuff in session...
end

Mhm… two times the exact same unless block just with a different condition? Not very DRY, isn’t it?

Ok, we’re nearly there where this post started. Why not just throw a UserErrors::LoginFailed Error? This would look like this:

1
2
3
4
5
6
def login
  raise UserError::LoginError unless request.post?
  user = User.authenticate(params[:nickname], params[:password])
  raise UserError::LoginError(user) unless user
  #doing the login stuff in session...
end

Quite cool. Now we outsourced the things that should happen on a login failure to this private method in the user controller:

1
2
3
4
5
def login_error(e)
  flash[:notice] = :login_failed
  redirect_to_last_page
  return
end

And at to get this method work when a UserError::LoginFailed method is thrown we added this as private methods to the application controller:

1
2
3
4
5
6
7
8
9
10
alias old_rescue_action rescue_action
def rescue_action(e)
  key = @@rescue_exceptions.keys.find {|el| e.is_a?(el)}
  return old_rescue_action(e) unless key
  send(@@rescue_exceptions[key][:with], e)
end
 
def self.rescue_from_all(e, params)
  @@rescue_exceptions[e] = params
end

This let us now do this:

1
rescue_from_all UserError::LoginFailed, :with => :login_error

at the top of the user controller.

That’s all. If now a UserError::LoginFailed exception is raised in the controller it gets handled by the login_error method. Not quite a big deal but I like it.

If I find some time this week I will put this to a small plugin, so that you can give it a try even easier.

If you have any questions, or want do discuss if this is nifty or just crap, you’re welcome to leave your comment.

Yours,

Thorben
FEtMab-Team

No Comments »

It’s a pitty that I couldn’t be at the RailsConf Europe in Berlin. But the holidays weren’t that bad, either.

So as I discovered the first version of Davids keynote online today I couldn’t resist and had to watch this even if there actually was no time for and now I’m even writing this post…

But there’s one thing I saw in the video which I think it’s worth to be mentioned: What was “freaking awesome” a year ago is now “neat”. Seems something like Rails is leaving puperty.

Sure, I’m not the first who notices that, even David himself speaks about it at the beginning of his talk. But as I followed his talk I got more and more convinced, that he’s not only saying that Rails is now not a rebel any more, he is “living” that.

Rails has very fast gone a long way from rebellion to maturity and now really seems to be there.

It’s definitely a good thing and I hope with the Rails 2.0 release which seems to be more finetuning than turning anything upside down this maturity also gets spread to the decision makers who could not be convinced today.

I think Rails is still on a good way and this without airs and graces.

Let’s look forward to more Rails magic in the near and further future.

Thorben
FEtMab-Team