JP Silvashy
JP Silvashy

Reputation: 48495

Rails: creating a model in the new action

I have an interesting situation, well it's probably not that unique at all, but I'm not totally sure how to tackle it. I have a model, in this case a recipe and the user navigates to the new path /recipes/new however the situation is that I need to be able to have the user upload images and make associations to that model in the new action, but the model doesn't have an ID yet.

So I assume I need to rethink my controller, but I don't want to have redirects and whatnot, how can accomplish this?

Here is the basic controller, barebones obviously:

...

def new
  # I should be creating the model first, so it has an ID
  @recipe = Recipe.new
end

def create
  @recipe = Recipe.new(params[:recipe])
  if @recipe.save
    redirect_to @recipe
  else
    render 'new'
  end
end

...

update

Perhaps I can have a column thats like state which could have values like new/incomplete/complete or what-have-you. I'm mostly trying to figure out what would also be most efficient for the DB.

It would be nice if I could still have a url that said '/new', instead of it be the edit path with the id, for usability sake, but I'm not sure this can be simply accomplished in the new action of my controller.

Thoughts?

Upvotes: 0

Views: 142

Answers (1)

klew
klew

Reputation: 14967

I'm not sure if I understand you correctly, but:

In new action you can create new object and attach files to it and post it in one form. You don't have to have it stored in db at this point. It can be saved in create action like any other fileds in model. In this case field "name" and "attached_file" (just examples) are treated in the same way (almost). Take a look at some paperclip (or whatever) tutorial in the web.

Upvotes: 1

Related Questions