Christopher
Christopher

Reputation: 1645

RESTful Actions Best Practices

I've got a RESTful User model working well in Rails 3. I'd like to add a new option to create a new user based on information queried out of a LDAP server.

What I'd like advice on is how best to do this. Here's what I've thought up so far, but I don't know if it matches Rails best practices:

Edit the resource path of User to accept both GET and POST to a new view called "import_ldap_user".

Import LDAP user then presents a form which uses AJAX (POSTing to import_ldap_user) to allow the visitor to search for a person in LDAP. The results are displayed on the page and if acceptable, the user clicks "Create", which then calls /user/create.

Part of why this seems bad to me is:

  1. I need to post a proper @user to /user/create, but I'm not sure if my AJAX call can produce a proper @user.
  2. I don't know if it's a bad practice to add a new verb to the RESTful Users route.
  3. I don't know if using an AJAX POST to import_ldap_users is a proper separation of concerns.

Any ideas? Any Rails perfectionists have opinions about how this should work?

Upvotes: 2

Views: 304

Answers (1)

Karl
Karl

Reputation: 6165

What gets posted to /user/create isn't an @user object but rather its attributes. A scaffolded create action will probably have something akin to @user.new(params[:user]), which just pulls the user attributes that were posted and creates a new object based on that.

Even if your AJAX call doesn't provide the attributes in a manner that can be processed by the new method, you can simply modify your create such that it manipulates the post data.

As for best practices, this is definitely something I've thought about in the past but I don't know if there's a "correct" answer. I think having a new view which posts to the create method is perfectly acceptable, you could also create a new controller if you want to strictly follow the CRUD pattern.

Definitely a good question and if anyone has a better answer I'd love to hear it.

Upvotes: 2

Related Questions