简体   繁体   中英

Add information to DB from the controller on rails

I'm trying to add the user id to 2 columns in the db after a user successfully submits a form. The commands run fine in the console but wont work in the controller. I haven't added info to the db straight from the controller before so I'm thinking that I'm doing something wrong.

Here is the create method

 def create
   @game = Game.friendly.find(params[:game_id])
   @game_category = Game.friendly.find(@game.id).game_categories.new(game_category_params)

    if current_user.mod_of_game? params[:game_id] && @game_category.save

    Game.find(@game.id).game_categories.find(game_category.id).update(submitted_by: current_user.id)
    Game.find(@game.id).game_categories.find(game_category.id).update(approved_by: current_user.id)

      flash[:info] = "Game category added succesfully!"
      redirect_to @game
    else
      render 'new'
    end

end

These 2 lines are supposed to add the user id to the submitted_by and approved_by columns but they don't. I don't get any error messages, they simply just don't add anything to those columns

Game.find(@game.id).game_categories.find(game_category.id).update(submitted_by: current_user.id)
Game.find(@game.id).game_categories.find(game_category.id).update(approved_by: current_user.id)

If I replace the lines with coding that works in the console to see if its a variable or something thats not right it still doesn't work

Game.find(12).game_categories.find(55).update(submitted_by: 1)
Game.find(12).game_categories.find(55).update(approved_by: 1)

I'm building an app to learn rails and I guess this is something I just don't know.

Can anyone enlighten me on what I'm doing wrong?

Update:

Ok it is now giving me an error - Couldn't find GameCategory without an ID

So the @game_category.id isn't working?

这是您错过@的查询中的一个小错字。

Game.find(@game.id).game_categories.find(@game_category.id).update(submitted_by: current_user.id)

After playing around tweaking it here and there it turns out to be this line

if current_user.mod_of_game? params[:game_id] && @game_category.save

when changed to this it works

if @game_category.save && current_user.mod_of_game? @game 

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