我有客户端模型和项目模型。我的客户has_many:项目和项目belongs_to:客户。
在客户端#show视图中,当我可以选择现有项目(尚未分配客户端)并将其分配给此客户端时,我想要一个表单。
我试过了:
= simple_form_for @client, url: assign_new_project_client_path do |f|
= f.input :project, collection: Project.without_client.map {|p| [p.name, p] }
= f.submit 'Add project'
我在客户端控制器中创建了新操作:
def assign_new_project
@client.projects << project
@client.save
end
不幸的是,simple_form_for中的输入似乎只能接受客户端对象的实际属性。我得到的错误是:
undefined method `project' for #<Client:0x0000000524a9f0>
我想将项目作为变量或其中一个参数传递给我的assign_new_project操作。我很感激任何提示。
答案 0 :(得分:1)
答案 1 :(得分:0)
你应该在你看来:
= simple_form_for @client, url: assign_new_project_client_path do |f|
= f.association :projects,
:collection => Project.without_client,
:label_method => :name
= f.submit 'Add project'
并在您的控制器中:
class ClientsController < ApplicationController
# ...
def assign_new_project
@client.projects.build(project_params)
if @client.save
flash[:notice] = 'Project assigned successfully'
redirect_to root_path
else
render :new
end
end
private
def project_params
params.require(:client).permit(
# other client fields,
:project_ids => []
)
end
end
请务必将accepts_nested_attributes_for :projects
添加到Client
型号。