多态关联:创建文档表单

时间:2015-09-17 16:54:29

标签: ruby-on-rails ruby-on-rails-4 polymorphic-associations model-associations

我需要你的帮助!

当用户创建新文档时,他应该将其分配给项目或任务。

如果用户当前正在选择一个项目,那么id将不会仅在documentable_id中保存在documentable_type中,但任务可以完美地运行。

我的错误在哪里?

Document.rb

belongs_to :documentable, polymorphic: true
belongs_to :project
belongs_to :task

Project.rb

has_many :documents, :as => :documentable


Task.rb

has_many :documents, :as => :documentable


documents_controller.rb

def create
  @document = Document.new(document_params)
  @document.user_id = current_user.id
  if @document.save
    redirect_to @document
  else
    render "new"
  end
end
def document_params
  params.require(:document).permit(:attachment, :is_unlocked, :is_paid, :brutto, :netto, :has_skonto, :supplier_id, :due_at, :tax, :number, :documentable_id, :documentable_type)
end

文件/ _form.html.erb

 <div class="form-group">
    <%= f.collection_select :documentable_id, Project.all, :id, :name, { prompt: "Projekt zuordnen"} %>
  </div>

  <div class="form-group">
    <%= f.collection_select :documentable_id, Task.all, :id, :id, { prompt: "Aufgabe zuordnen"} %>
  </div>

1 个答案:

答案 0 :(得分:0)

如果您有2个具有相同名称的下拉列表,则只有第二个下拉列表将包含在参数中。导轨功能对某些事情很有用。

您可以添加下拉菜单或动态启用/禁用它们以解决此问题。

相关问题