Eddard Stark
Eddard Stark

Reputation: 3595

form_for error in rails 3

I am trying to save a model named 'customer' using form_for tag. I do not have a controller for this model, i was hoping to use another controller 'public' for this task. So here is my view:

<%= form_for @customer do |f| %>
<div class="field">
    <%= f.label :name %><br/>
    <%= f.text_field :name %>
</div>
  .... and then
 <%= f.submit 'Order', :action => :save_order %><br/>

and here is my controller

def check_out
@customer = Customer.new
end

def save_order
@customer = Customer.new(params[:customer])
credit_card_no = @customer.credit_card
@order = Order.new
@order.line_items << @cart.items
@customer.orders << @order
if @customer.save
    # process credit card
    @cart = nil
    redirect_to(:action => :show_bill, :id => @order.id)
else
    flash[:notice] = 'Could not process your credit card information'
    render(:action => :check_out)
end
end

The view is loaded from action 'check_out' and it was supposed to go to action 'save_order' but i am getting an error in view for 'form_for' code, what am i doing wrong ? But if i create a controller or scaffold for 'customer' and try to use that, i get redirected to 'customer/show/:id' path, and i dont want that.

Upvotes: 0

Views: 544

Answers (2)

Soundar Rathinasamy
Soundar Rathinasamy

Reputation: 6728

If you want to use different controller with form_for you need to use :url option in form_for.

<%= form_for @customer, :url => { :controller => "your controller name",
:action => "save_order" } do |f| %>

#your code

<% end %>

Upvotes: 1

Mark Fraser
Mark Fraser

Reputation: 3198

Sorry, but you are asking for help in how to make something work while doing it wrong. I will try to explain and I hope this will help you.

If you want to save a customer model you should use, guess what, a customers controller. Some people like to use scaffolds, some people hate them. But the fact that the scaffold code redirects to the show method after saving a model, which is easily changed, shouldn't stop you from using it. The scaffold is just there to help beginners and/or to have a way to come up with something quick and dirty. Changing the scaffold generated code here and there is not only usually necessary it's a good way to learn.

To save an order you should use, ::drumroll::, an orders controller. I don't even know what a "public" controller would do (which by itself should tell you at least that it is poorly named).

I suggest you get the Agile Web Development with Rails book and go through the depot application. It covers all of this very subject well and you will learn a lot.

Upvotes: 1

Related Questions