I have some show action that displays one category. But from there I want via link to create new product. Point is that I passed category id and name via link_to.
It goes well, it opens Product/new action. And in browsing bar there is link like this http://mysite/products/new?id=43&name=Skeleji
.its okay.
But how can I make those id and name available in form, where I am filling information about new product? After this when I click create, I want that theese values such category_id saves in db along with other information abaut product.
Between, Product and Category I have built relationship.
So far my code looks like this .
My Category/show action code looks like this.
<%= link_to "Add Product", {:controller => "products", :action => "new", :id => @category.id, :name => @category.name }%>
Product controller, new action looks like this.
def new
@product = Product.new
@product.category_id = @category.id
end
Clicking create it creates project, but without category_id. Where could be the problem ? Maybe the code what is under new action,actually should be under create action. About year ago I managed to do such thing, but I can't find that project.:(
You should be able to just set the values in your new
action:
def new
@product = Product.new
@product.category_id = params[:id]
@product.name = params[:name]
end
Then they will appear as such in your form.
But I don't think it's a good idea to call your parameter id
because it's a default parameter name for resourceful routing. params[:id]
in the ProductsController
should typically always refer to a Product
object. As it happens, you're using it in the new
action which in normal use will never receive an id
parameter so I doubt you'll get in any trouble, but it isn't very semantic.
If you let Product
accept nested attributes for Category
then I think you'd be able to simply do:
@product = Product.new(params[:product])
if you structured your params like: :product => { :name => "whatever", :category_attributes => { :id => 1 } }
but that might be overkill depending on your needs.