Chris
Chris

Reputation: 1284

How do I change the form rendered by Rails?

I have two classes, User and Contact. A User has many contacts, and a Contact belongs to a user. In the user's show view, I have:

<%= link_to 'Add Contact', :controller => "contacts", :action => "new", :user => @user.id %>

Then, in the contact's controller, under the new action, I have:

@user = User.find(params[:user])
@contact = Contact.new  
@contact.user = @user

When the new contact form renders, it has #<User:0x4c52940> in the User field already. However, when I go to submit the form, I get the error: User(#39276468) expected, got String(#20116704).

The problem is that, when create gets called, Ruby takes everything in the form and overwrites the fields in the new Contact. So: how can I change the form to remove the User field, so that the User is not overwritten with the string?

Edit: My Contact's new.html.erb has this:

 <%= render 'form' %>
 <%= link_to 'Back', contacts_path %>

Contact's controller:

def new
@user = User.find(params[:user])
@contact = Contact.new

@contact.user = @user


respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @contact }
end
end

and

def create
@contact = Contact.new(params[:contact])

respond_to do |format|
  if @contact.save
    format.html { redirect_to @contact, notice: 'Contact was successfully created.' }
    format.json { render json: @contact, status: :created, location: @contact }
  else
    format.html { render action: "new" }
    format.json { render json: @contact.errors, status: :unprocessable_entity }
  end
end
end

Upvotes: 0

Views: 57

Answers (1)

cryo28
cryo28

Reputation: 1127

I believe you misuse create action of the controller. Essentially its content should be like so

def create
   @user = User.find(params[:user_id])
   contact = @user.contacts.build(params[:contact])
   if contact.save
     flash[:alert] = 'New contact is created'
     redirect_to contacts_path(contact)
   else
     flash.now[:error' = 'Error creating contract'
     render :action => :new
   end
end

So +1 for the previous answer - show you controller and new form code

Upvotes: 1

Related Questions