Nick
Nick

Reputation: 3100

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

My logic below where a variable's id gets passed on from the link, to def new, to a form, and then to def create breaks down in the last step.

In a view I have a link that passes on an organization's id:

createme_path(organization_id: @organization.id)

Def new (it actually has a different name but for the question I don't think this matters) in the controller uses this variable:

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

The form that def new renders includes:

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

Def create uses this as follows:

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

In def create something goed wrong. Upon creating a new user, I get the error message below referring to the me = line. What is wrong with the code and makes that organization_id is unavailable in def create?

Couldn't find Organization without an ID

Upvotes: 0

Views: 88

Answers (2)

Naim Rajiv
Naim Rajiv

Reputation: 3374

You are doing a mistake to get params value in create action. It must look like:

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

    .....
    .....
end

Also please modify your new_params method, i think you need to modify there also. You should understand how rails pass params by using hash. Look carefully the bellow log:

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

Your params is wrap by user. Thus you must get it by using params[:user][...]

Please let me know if you have any query.

Upvotes: 3

Pavan
Pavan

Reputation: 33552

You params hash is from user, so it should be

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

Upvotes: 0

Related Questions