将当前客户端 :id 传递给收集表单字段的应用程序助手?
Application helper to pass current client :id to collection form field?
我有一个 rails 应用程序具有以下模型:
Users
、clients
和 invoices
,在此应用程序中,user
能够从 invoices index view
和 clients show view
。每个 Invoice
都需要在保存时设置 :client_id
。我没有在 invoices_controller
new action
中调用 client.find(params:id)
因为在从 invoices index view
.
创建 invoice
时找不到它
在 client/id/invoice.new
路径上获取 current client :id
的最佳方法是什么?我应该在辅助方法中传递 client :id
吗?或者我可以在我的 new action
或 form
中做一些我没有看到的很酷的事情吗?
型号
User
has_many :invoices
has_many :clients
Client
belongs_to :user
has_many :invoices
Invoice
belongs_to :client
belongs_to :user
在我的 invoices_controller 新操作中,我只是调用
def new
@invoice = Invoice.new
end
我的新发票 _form
<%= f.input_field :client_id, :collection => Client.all, :label_method => :client_name, :value_method => :id, :include_blank => false, selected: @client_id, class: "form-control" %>
还有我的路线
resources :invoices, only: [:new, :create, :destroy, :index]
resources :clients do
resources :invoices, shallow: true
end
root 'invoices#index'
When I create a new invoice at clients/id/invoices/new
, I want to set the default form field selector to be the current client's id from the URL?
您需要在将 collection: []
传递给 input_field
方法后立即传递 selected: value
选项,如下所示:
<%= f.input_field :client_id, :collection => Client.all, :selected: @client_id, :label_method => :client_name, :value_method => :id, :include_blank => false, class: "form-control" %>
编辑:
您可能需要在 URL 帮助程序中传递 @client
变量,如下所示:
new_invoice_path(client_id: @client.id, back_path: client_path(@client))
我有一个 rails 应用程序具有以下模型:
Users
、clients
和 invoices
,在此应用程序中,user
能够从 invoices index view
和 clients show view
。每个 Invoice
都需要在保存时设置 :client_id
。我没有在 invoices_controller
new action
中调用 client.find(params:id)
因为在从 invoices index view
.
invoice
时找不到它
在 client/id/invoice.new
路径上获取 current client :id
的最佳方法是什么?我应该在辅助方法中传递 client :id
吗?或者我可以在我的 new action
或 form
中做一些我没有看到的很酷的事情吗?
型号
User
has_many :invoices
has_many :clients
Client
belongs_to :user
has_many :invoices
Invoice
belongs_to :client
belongs_to :user
在我的 invoices_controller 新操作中,我只是调用
def new
@invoice = Invoice.new
end
我的新发票 _form
<%= f.input_field :client_id, :collection => Client.all, :label_method => :client_name, :value_method => :id, :include_blank => false, selected: @client_id, class: "form-control" %>
还有我的路线
resources :invoices, only: [:new, :create, :destroy, :index]
resources :clients do
resources :invoices, shallow: true
end
root 'invoices#index'
When I create a new invoice at
clients/id/invoices/new
, I want to set the default form field selector to be the current client's id from the URL?
您需要在将 collection: []
传递给 input_field
方法后立即传递 selected: value
选项,如下所示:
<%= f.input_field :client_id, :collection => Client.all, :selected: @client_id, :label_method => :client_name, :value_method => :id, :include_blank => false, class: "form-control" %>
编辑:
您可能需要在 URL 帮助程序中传递 @client
变量,如下所示:
new_invoice_path(client_id: @client.id, back_path: client_path(@client))