多态关联:创建文档表单
Polymorphic Association: Create document form
我需要你的帮助!
当用户创建新文档时,他应该将其分配给项目或任务。
如果用户当前正在选择项目,则 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
documents/_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>
如果您有 2 个同名的下拉菜单,则参数中只会包含第二个。 rails 功能对某些事情很有用。
您可以添加下拉菜单或 enable/disable 它们动态地解决这个问题。
我需要你的帮助!
当用户创建新文档时,他应该将其分配给项目或任务。
如果用户当前正在选择项目,则 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
documents/_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>
如果您有 2 个同名的下拉菜单,则参数中只会包含第二个。 rails 功能对某些事情很有用。
您可以添加下拉菜单或 enable/disable 它们动态地解决这个问题。