0

User と Contact の 2 つのクラスがあります。ユーザーには多くの連絡先があり、連絡先はユーザーに属します。ユーザーの表示ビューには、次のものがあります。

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

次に、連絡先のコントローラーの新しいアクションの下に、次のものがあります。

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

新しい連絡先フォームがレンダリングされると、ユーザー フィールドに #<User:0x4c52940> が既に含まれています。ただし、フォームを送信しようとすると、次のエラーが表示されます: User(#39276468) expected, got String(#20116704)。

問題は、create が呼び出されると、Ruby がフォーム内のすべてを取得し、新しい Contact のフィールドを上書きすることです。では、ユーザーが文字列で上書きされないように、フォームを変更してユーザーフィールドを削除するにはどうすればよいですか?

編集:私の連絡先のnew.html.erbには次のものがあります:

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

連絡先のコントローラー:

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

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
4

1 に答える 1

1

コントローラーの作成アクションを誤用していると思います。本質的にその内容はそのようでなければなりません

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

したがって、前の回答の+1-コントローラーと新しいフォームコードを表示します

于 2012-12-11T19:46:35.447 に答える