param getting passed as nil in Rails form
I have a form where I am trying to do a very simple CRUD operations on rails with MongoDB.
I have my controller
class RecipesController < ApplicationController
def new
@recipe = Recipe.new
end
def update
end
def create
recipe = Recipe.create(params[:title])
redirect_to params[:title]
@recipes = Recipe.all
end
def index
@recipes = Recipe.all
end
end
my form
<%= form_for Recipe.new do |f| -%>
<%= f.text_field :title %>
<%= f.submit "Create Recipe" %>
<% end %>
seems 开发者_Go百科pretty basic to me. However, the params are not getting through to the controller it seems.
I can see the params passed through webrick
Started POST "/recipes" for 127.0.0.1 at 2010-09-02 14:15:56 -0800
Processing by RecipesController#create as HTML
Parameters: {"authenticity_token"=>"8oyq+sQCAEp9Pv864UHDoL3TTU5SdOXQ6hDHU3cIlM
Y=", "recipe"=>{"title"=>"test"}, "commit"=>"Create Recipe"}
Rendered recipes/create.html.erb within layouts/application (4.0ms)
Completed 200 OK in 51ms (Views: 16.0ms)
but the redirect_to params[:title] returns a nil value error.
I noticed that 'title' is inside the 'recipe' parameter, and wasn't sure if that may be part of the issue.
One of the the many things that has me confused is that I never actually have to call create? Is that right? I'm calling 'new' on the form, and for some reason rails automatically calls 'create'?
Try putting the redirect in your controller after @recipes = Recipe.all like so, and making your variables and instance variable :
def create
@recipe = Recipe.new(params[:title])
@recipes = Recipe.all
respond_to do |format|
if @recipe.save
format.html redirect_to params[:title]
end
end
end
Your syntax is fairly ugly. I would suggest using the out-of-the-box Rails generators to scaffold your work, and base your project off of that until you get good at what you do.
Rails 2:
script/generate scaffold Recipe name:string ingredients:text
Rails 3:
rails g scaffold Recipe name:string ingredients:text
Then make sure you rake db:migrate
As you suggest the title
parameter is inside your recipe
set of parameters. So, to create your recipe you need to do:
Recipe.create(params[:recipe])
NB. this will return false and not create a recipe if the validations on the recipe fail - e.g. if you require a title. You don't check for this and you might want to.
So, similarly, if you want to redirect the title of the new recipe (I have no idea why you'd want to as that probably isn't a valid location but I'll go along with your example), you need to do:
redirect_to params[:recipe][:title]
or you can access the title on the newly created recipe r.title
.
Also, if you are redirecting to another action there is no benefit in setting up instance variables (@recipes
) as they will be lost during the redirect.
精彩评论