0

我正在尝试从帐户对象的“显示”页面创建一个新的联系人对象。我知道下面的代码不正确。如果我在帐户的“显示”页面上,如何将该帐户 ID 传递给新联系人表单,以便创建属于该帐户的新联系人?

联系belongs_to账户

帐户has_many联系人

帐户“显示”视图,其中我有指向新联系人的链接

<%= link_to "Add Contact", new_account_contact_path(@account), class: 'btn' %>

使用建议的编辑“新建、创建”操作联系控制器

class ContactsController < ApplicationController
  before_filter :authenticate_user!
  before_filter :load_account
  respond_to :html, :json

...

  def create
    @contact = @account.contacts.new(params[:contact])
     if @contact.save
       redirect_to account_path(params[:account]), notice: "Successfully created Contact."
     else
       render :new
     end

  end

  def new
    @contact = @account.contacts.new
  end
...

end

新的联系表

<%= simple_form_for(@contact) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :firstname %>
    <%= f.input :lastname %>
    <%= f.input :email %>
    <%= f.input :phone %>
    <%= f.input :note %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

错误

undefined method `contacts_path' for #<#<Class:0x007f86c0c408d0>:0x007f86c0be7488>
Extracted source (around line #1):

1: <%= simple_form_for(@contact) do |f| %>
2:   <%= f.error_notification %>
3: 
4:   <div class="form-inputs">
4

3 回答 3

2

从 的存在来看new_account_contact_path(@account),我会假设你的 : 中有这样的东西routes.rb

resources :accounts do
  resources :contacts
end

如果是这种情况,您的contacts#create路线(以及每条contact路线)将包含一个:account_id参数。您可以before_filter在 中的每个操作中添加一个以自动加载帐户ContactsController,因此您始终拥有相关的帐户对象:

before_filter :load_account

def load_account
  @account = Account.find(params[:account_id])
end

然后在您的 new 和 create 操作中,在关系上构建对象很简单:

def new
  @contact = @account.contacts.new
end 

def create
  @contact = @account.contacts.new(params[:contact])
  ....
end

另外,我从未使用过simple_form_for,但令我震惊的是,您可能还需要@account作为参数传入,以便表单知道要发布到哪个 url。

于 2013-05-15T18:06:33.503 回答
0

我假设你的路线看起来像

resources :accounts do
  resources :contacts
end

这样,new_account_contact_path(@account)将产生一个类似的 URL /accounts/SOME_ID/contact/new

然后,您将可以通过ContactsController访问帐户 ID params[:account_id],因此为已知帐户创建联系人的正确方法是

def new
  @account = Account.find(params[:account_id])
  @contact = @account.contacts.build(params[:contact])
end

def create
  @account = Account.find(params[:account_id])
  @contact = @account.contacts.build(params[:contact])
  # some stuff
end
于 2013-05-15T18:06:06.743 回答
-1

你应该改变你的new行动:

def new
  @account = Account.find(params[:account])
  @contact = Contact.new
end

并以您的new形式:

<%= simple_form_for(@contact) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :firstname %>
    <%= f.input :lastname %>
    <%= f.input :email %>
    <%= f.input :phone %>
    <%= f.input :note %>
    <%= f.input :account_id, :as => :hidden, :input_html => { :value => @account.id } %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>
于 2013-05-15T18:02:07.440 回答