Question: Stopping insertion in rest controller

Tough finding a subject line that's fitting.

Anyway , I have a REST controller with a model called Cdetail. I am only allowing 1 record per user for this table and want the app to redirect with a flash message if they've already inserted one.

So here is my new method: def new @cdetail = Cdetail.new # Don't think I actually need this here @uid = current_user.id end

and here is the create method: def create

    if     Cdetail.find_by_user_id(@uid) == true     flash[:notice] = "Allowed only one record"     redirect_to(:controller => 'index', :action => 'index')     end

    @cdetail = Cdetail.new(params[:cdetail])     @cdetail.save!

I'm a newb so trying to remember what I've learned as I go along (still going back to book) but I expect the if statement if it finds a record for the current_user in the method (column) user_id it would redirect away from the create method, however it's not doing so. It's not throwing an error either but ... I suppose this is what happens when a Ruby Newbie jumps to quickly into Rails :slight_smile:

Some direction or advice would be greatly appreciated. Stuart

First thing I noticed was the use of @uid in create - this won’t do what you think. Instance variables are not persistent across requests. Either store the user id in session or just use current_user.id.

Second, the condition above will never be true - Ruby’s evaluation of conditionals is more like “!= nil” than “== true” - any value other than nil is evaluated as true. However, Cdetail.find_by_user_id will return an instance of Cdetail, which is definitely not == to true (the single instance of TrueClass). Leaving off the “== true” part will do what you want.

A final note - judging from the class names, I’m guessing that you’re creating

a mechanism for users to add details to a profile of some sort. It isn’t clear to me that straight CRUD is a suitable method for doing this - wouldn’t it make more sense for a user to ‘edit’ their details, even if they didn’t previously exist?

If the methods are split, it still might be better to remove the “create” option altogether if a user’s details already exist. It might even be better to move the Cdetail controller’s work into the User controller, using the ; notation to

map the action, so that

GET /users/1;edit_details

would show the form for User id 1, and

PUT /users/1;details

would commit the edit.

Good luck!

Thanks for a great explanation Matt. You understand exactly what I'm doing. I'm not entirely sure yet why I want to keep the two seperate other then I want people to be able to get a feel for the sytem (but requiring a brief registration ) and then later make more of a committment if they feel it's beneficial to do a full blown profile. However some good suggestions and I'll be looking at perhaps a better way to get the informaton.

Stuart