【问题标题】:Rails 4. How to assign existing Project to Client (where Client has_many Projects) using form and dropdown list?Rails 4. 如何使用表单和下拉列表将现有项目分配给客户(其中客户有_许多项目)?
【发布时间】:2013-12-11 17:44:31
【问题描述】:

我有客户模型和项目模型。我的客户 has_many :projects 和 Project belongs_to :client.

在客户端#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 操作。如有任何提示,我将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby haml


    【解决方案1】:

    你想使用:

    f.association :projects
    

    更多详情:https://github.com/plataformatec/simple_form#associations

    【讨论】:

      【解决方案2】:

      在你看来你应该这样做:

      = 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 模型中。

      【讨论】:

      • 你不是说client_params吗?我做了你建议的一切(使用client_params)而不是project_params,现在我得到unknown attribute: project_ids
      猜你喜欢
      • 1970-01-01
      • 2020-02-12
      • 2020-04-15
      • 2012-10-11
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多