Id 不会传递给控制器​​的创建方法

Id doesn't get passed on to controller's create method

我在下面的逻辑中,变量的 id 从 link 传递到 def new,再到表单,然后传递到 def create,但在最后一步中断了。

在一个视图中,我有一个传递组织 ID 的 link:

createme_path(organization_id: @organization.id)

控制器中的 Def new(它实际上有一个不同的名称,但对于我认为这无关紧要的问题)使用此变量:

@organization = Organization.friendly.find(params[:organization_id])

def new 渲染的表单包括:

<%= f.hidden_field :organization_id, value: @organization.id %>

Def create 使用如下:

me = Organization.friendly.find(params[:organization_id])
@user = org.users.build(new_params)

def create 中出了点问题。创建新用户后,我收到以下关于 me = 行的错误消息。代码有什么问题导致 organization_iddef create 中不可用?

Couldn't find Organization without an ID

params hash来自user, 所以应该是

Organization.friendly.find(params[:user][:organization_id])

您在 create 操作中获取参数值时犯了错误。它必须看起来像:

def create 
    me = Organization.friendly.find(params[:user][:organization_id])
    @user = org.users.build(new_params)  

    .....
    .....
end

另请修改您的new_params方法,我认为您也需要修改那里。您应该了解 rails 如何使用哈希传递参数。仔细看下面的日志:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"ByeJN1oJ4CU2J1TgeXP***SJPpnOQINlMct8ZOskcxzVGGGFaM9B0g==", "user"=>{"organization_id"=>"2", "email"=>"test21@examepl.com", "username"=>"test21", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "commit"=>"Register"}

你的参数被用户包装了。因此,您必须使用 params[:user][...]

来获取它

如果您有任何疑问,请告诉我。