0

I have a rails application that has an admins model which has many users and users has_and_belongs_to_many materials. The problem is that for a specific user (for example user/show/2) I have a form on that page that posts to materials create action. In the create action here is what I am trying to do

def create
@material = @user.materials.create(material_params)
end

However, it won't work because @user is nil. This needs to associate a material with a user via the users_materials table (because of the has_and_belongs_to_many association). So, how would I define a material from a users page (user/show/:id) and be able to define a material for that user? What is a good way to do this in rails?

1
  • Can you show what your view code looks like for the post to materials? Commented Sep 9, 2013 at 16:26

1 Answer 1

1

It sounds as though what you have is Nested Resources.

There's a RailsCast about them here, and they're discussed in this guide.

The quick version is that you're going to define your routes approximately like so:

resources :users do
  resources :materials
end

And that the form will POST to /users/:user_id/materials, which I believe you'd call as users_materials_path(@user).

The controller action (MaterialsController#create) will be able to refer to params[:user_id], and can either simply assign that as the user_id of the Material, or actually load that user (User.find(params[:user_id]) and then call .materials.create on it.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the answer it worked.However something confuses me.Why params[:user_id] and not params [:id] ?
It's how the nested resource pattern works. The reasoning behind it is consistency. For instance, to see a particular Material of a particular user, the path is /users/:user_id/materials/:id. In that case, params[:id] is the material id, so the user id needs a different name - hence user_id. It would be weird, though, if your show action referred to the user id as params[:user_id] but create called it params[:id], so it's just always user_id.
Ah I see now why I was confused I was thinking that maybe it had some kind of connection with the materials_users table(for the has_and_belongs_to_many relationship) which has a user_id.Thanks for clearing that up!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.