我有这个网站,用户可以有很多宠物。这些宠物列在那里的配置文件中,点击宠物将它们带到宠物配置文件中,在那里他们可以选择编辑宠物。加载宠物的表格效果很好,它为每个人提供了正确的信息,但随后出现了更新问题。单击编辑表单上的提交会导致所有更新转到他们拥有的第一个宠物。比如,如果宠物的ID为2,5和11,而5或11的更新则转为2.我不太确定发生了什么。
以下是PetsController的编辑和更新操作:
#GET to /users/:user_id/pet/edit
def edit
@user = User.find( params[:user_id] )
@pet = Pet.find_by_id( params[:id] )
end
#PUT to /users/:user_id/pet/
def update
#Retrieve user from database
@user = User.find( params[:user_id] )
#Retrieve user's pet
@pet = @user.pets.find_by( params[:id] )
#Mass assign edited pet attributes and save (update)
if @pet.update_attributes(pet_params)
flash[:success] = "Pet updated!"
#Redirect user to profile page
redirect_to user_path(id: params[:user_id] )
else
render action: :edit
Rails.logger.info(@pet.errors.messages.inspect)
end
end
我尝试过不同的寻找用户宠物的方法,例如
@user.pet(params[:id])
这导致了一个错误,它说找不到没有身份证的宠物,所以接下来我尝试了
@user.pet.find_by_id(params[:id])
但是这导致update_attribute没有被定义,所以我认为我不应该使用find_by_id
我可能还有另一种方式吗?我认为错误是宠物的身份证没有被正确传递。如果是这样,有什么可以解决这个问题?我尝试将ID作为隐藏字段从编辑表单中传递,但这并不起作用。
这是当用户尝试更新宠物时在终端中发生的事情
Processing by PetsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"0tC+qRK01CMCEZWbDtJyZ4QNmXQxnaAPKT+anRKGKh5hTWekTbEHzAd+8 +YOVIWBB0/imVrMVNcpkeBR18SHNw==", "pet"=>{"color"=>"Darigan", "species"=>"Yurble", "gender"=>"Male", "level"=>"25", "hp"=>"50", "strength"=>"50", "defence"=>"50", "movement"=>"50", "uc"=>"1", "rw"=>"0", "rn"=>"0", "uft"=>"1", "ufa"=>"0", "description"=>"uiy7i77i7i", "id"=>"5", "name"=>"Fouany", "hsd"=>"150"}, "user_id"=>"5"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 5], ["LIMIT", 1]]
Pet Load (0.3ms) SELECT "pets".* FROM "pets" WHERE "pets"."user_id" = ? LIMIT ? [["user_id", 5], ["LIMIT", 1]]
(0.1ms) begin transaction
Pet Exists (0.2ms) SELECT 1 AS one FROM "pets" WHERE "pets"."name" = ? AND ("pets"."id" != ?) LIMIT ? [["name", "Fouany"], ["id", 2], ["LIMIT", 1]]
(0.1ms) rollback transaction
Rendering pets/edit.html.erb within layouts/application
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 5], ["LIMIT", 1]]
Rendered pets/edit.html.erb within layouts/application (12.4ms)
Profile Load (0.4ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = ? LIMIT ? [["user_id", 5], ["LIMIT", 1]]
{:name=>["has already been taken"], :color=>[], :species=>[], :gender=>[], :level=>[], :hp=>[], :strength=>[], :defence=>[], :movement=>[], :uc=>[], :rw=>[], :rn=>[], :uft=>[], :ufa=>[], :description=>[]}
Completed 200 OK in 202ms (Views: 136.1ms | ActiveRecord: 5.0ms)
正如你所看到的,宠物的身份证从5开始从5回到2,所以也许可以从某个地方开始解决这个问题?
非常感谢任何建议和意见!
答案 0 :(得分:0)
@user.pets.find_by(params[:id])
应该是
@user.pets.find_by(id: params[:id])
答案 1 :(得分:0)
如果您的用户应该只有一只宠物(路线建议这样),则不需要宠物ID来访问它。
你可以得到宠物@user = User.find( params[:user_id] )
@pet = @user.pet
在您的代码中查看此评论:
#PUT to /users/:user_id/pet/
提到了user_id
,但未提到id