当我尝试创建联接模型时,我在参数中得到空值

时间:2019-10-21 19:02:25

标签: ruby-on-rails has-many-through model-associations

我正在通过与Party和Guest的关系为has_many创建一个联接模型Invite,但是我得到了空的params [:party_id]。用户以访客身份登录,访客可以看到所有聚会列表,并且访客可以单击单个聚会,并且有一个加入聚会的链接。访客单击“加入此聚会”后,它将转到“ / parties / 2 / invites / new”,我有一个表格供访客填写。客人提交表格时,我被卡住了。网址已更改为“ / parties / 2 / invites”,但我仍然看到表单视图,刷新页面后,它将显示邀请索引页面。

我在bindings#create中放入binding.pry并输入params,我看到的是party_is“”。并且我看到允许“ commit” =>“ Join!”,“ controller” =>“ invites”,“ action” =>“ create”,“ party_id” =>“ 3”}:false>。

def new
    @invite = Invite.new
    @party_id = params[:party_id]

  end

  def create
    @invite = Invite.new(invite_params)
    binding.pry
    if @invite.save

       redirect_to guest_invites_path(current_user)
    else
      @party = Party.find(params[:party_id])
      render :new
    end
  end

private

  def invite_params
    params.require(:invite).permit(:add_on, :rsvp, :guest, :party_id)
  end
<%= form_with model: @invite, url: [@party, @invite], local: true do |f| %>
<%= f.label :add_on, "Add On" %>
<%= f.select :add_on, [1, 2, 3, 4], :prompt => 'Select One' %><br>

<%= f.label :rsvp, "RSVP" %>
<%= f.select :rsvp, [['Yes', true], ['No', false]], :include_blank => true %>

<%= f.hidden_field :party_id, :value => @party_id %>

<%= f.submit "Join!" %>
<% end %>
class Invite < ApplicationRecord
    belongs_to :party
    belongs_to :guest

    validates :add_on, :rsvp, presence: true
    accepts_nested_attributes_for :guest, :party
end

[4] pry(#)>引发params.inspect RuntimeError:“ 68nwEzR31GS2mcJGq9WhUrP0sp9zSjZENqY4 / iosH8sn0zHRxz + PRXXWsQVJDG100FTc + dG4epdA / Cr1DsiRbQ ==”,“邀请” =>“ 1”,“ rsvp” =“>”“,”“,” =>“加入!”,“控制器” =>“邀请”,“操作” =>“创建”,“ party_id” =>“ 3”}允许:false> 来自(撬):4:在'创建'中

1 个答案:

答案 0 :(得分:0)

对您的代码进行一些更改

从您的表单中,删除此行

<%= f.hidden_field :party_id, :value => @party_id %>

然后在您的控制器中重写您的create方法

def create
  @party = Party.find(params[:party_id])
  @invite = Invite.new(invite_params)
  @invite.party_id = @party.id 
  if @invite.save

    redirect_to guest_invites_path(current_user)
  else
    render :new
  end
end

因此,由于您的URL已经具有party_id,因此您无需在表单中输入它。试试这个,让我知道!