2016-11-06 28 views
0

我想用茧宝石的简单形式来嵌套父类窗体中的子窗体。Rails - Cocoon Gem - 填充外键id

我有建议和音调模型。

的关联是:

建议

has_one :pitch, inverse_of: :proposal 
    accepts_nested_attributes_for :pitch, reject_if: :all_blank, allow_destroy: true 

间距

belongs_to :proposal, inverse_of: :pitch 

在我的申请表,我有:

<%= f.simple_fields_for :pitch do |f| %> 
     <%= f.error_notification %> 
      <%= render 'pitches/pitch_fields', f: f %> 

     <% end %> 

     <%= link_to_add_association 'Pitch', f, :pitch, partial: 'pitches/pitch_fields' %> 

在我的提议控制器,我有:

def new 
    @proposal = Proposal.new 
    @proposal.build_pitch 
    # authorize @proposal 
    end 

    def edit 
    @proposal.build_pitch unless @proposal.pitch 
    end 


def proposal_params 
     params.require(:proposal).permit(:title, :description, 

     pitch_attributes:  [:id, :problem, :solution, :remark, :_destroy ]) 
    end 

音高/ _pitch_fields.html.erb有:

<div class="nested-fields"> 
    <div class="form-inputs"> 
     <%= f.input :problem, as: :text, 
      # :label => text_for_problem(current_user, @pitch.proposal), 
      :label => 'What issue does this proposal address?', 
      :input_html => {:rows => 10} %> 
     </div> 

当我保存这一切和尝试,形式加载,我可以填写表格,但PROPOSAL_ID外键保存为零。

如果我尝试编辑的形式,我得到一个错误,指出:

Couldn't find Pitch with ID=5 for Proposal with ID=10 

当我尝试:

pitch.errors.full_messages 
NameError: undefined local variable or method `pitch' for main:Object 

我需要什么,以迫使PROPOSAL_ID属性做在音高表中使用提案ID设置?

+0

编辑后保存表单时出现错误? – nathanvda

+0

是 - 没错 – Mel

回答

2

这有点奇怪,而且我在轨道中有一个bug,但link_to_add_association会尝试构建一个新的pitch以便能够正确呈现它。这将有效地删除现有的音调。

因此,解决方案是在link_to_add_association上添加选项force_non_association_create: true。或者完全放弃link_to_add_association:你为什么需要它?你只能有一个音高,而且如果它不存在,你总是会创建它?

+0

谢谢Nathan。我现在就试试这个。我想要链接按钮,因为如果建议(has_one pitch)是在没有音高的情况下创建的,那么编辑提议时,我希望链接能够在提案编辑表单中创建音高。我现在试试你的建议。 – Mel

+0

但是在你的控制器代码中,如果不存在,你总是添加一个音调,所以......? – nathanvda

+0

我不确定我明白你的意思。你的意思是我应该在我的组织控制器中添加一个构建新的高音线到新的动作中吗? – Mel

0

您没有显示您的_picthces/pitch_fields_部分,但请确保它具有proposal_id的隐藏字段。

另外,在您的proposal_params方法中,将proposal_id添加到pitch_attributes数组中。

如果还有其他问题,请在控制器的edit方法中设置断点,并检查proposal_params中的内容与@proposal对象中设置的内容。

+0

为什么我需要隐藏字段?其他时候我用过茧 - 我不需要隐藏的领域。茧与其他用途之间的主要区别是该提案只有一个音高(其他情况下是has_many关系)。我不认为使用隐藏字段是答案,因为在其他任何用例中都不需要。 – Mel

+0

啊,真的'fields_for'可能会增加它自己。但无论如何,你需要在你的pitch_attributes数组中允许它,对吧? – pdobb

+0

不,我不需要使用茧宝石的任何其他形式。它在没有使用茧的其他情况下将外键字段列入白名单的情况下进行更新。这种情况下的关键区别在于关联是has_one而不是has_many,但我无法弄清楚为什么会阻止外键ID被设置。 – Mel