简体   繁体   中英

Passing an instance variable from one controller to another in rails

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM