繁体   English   中英

无法使用Rails 4更新记录

[英]cant update a record with rails 4

我想更新控制器中的记录。 我尝试使用save或update_attributes,但是它不起作用。

我的代码是:

  @relation = Relation.where(:realtor_id => @message.realtor_id, :user_id => current_user.id)
  puts @relation.inspect
  @relation.save  

puts relation.inspect给我带来了好东西。 我收到此消息

NoMethodError (undefined method `save' for #<ActiveRecord::Relation::ActiveRecord_Relation_Relation:0x007fe6d6872fe8>):

我对“ update_attributes”有同样的问题。

我有3个模型:User,Realtor和Relation。 我使用“ has_many:through”通过“关系”在用户和房地产经纪人之间创建链接。

我的目标是在保存之前添加relation.status = "something" 当我添加@relation.status = "test" ,我得到:

NoMethodError (undefined method `status=' for #<ActiveRecord::Relation []>):
i think, it's a stupid error, but i cant solve it :)

我不在User,Realtor或Message控制器中,但在另一个控制器(消息控制器)中

谢谢前进

@relation = Relation.find(params[:id])
@relation.users.create(current_user) #or build and then .save

我找到答案了...

我使用: @relation = Relation.where(:realtor_id => @message.realtor_id, :user_id => current_user.id).take

而不是: @relation = Relation.where(:realtor_id => @message.realtor_id, :user_id => current_user.id)

只是为了让您对这是为什么有一些了解...如果您现在还不知道。

.where()每次都会用一个数组响应。 即使只有1个结果,它仍然在数组中,因此它不是模型的实例。 .find()以一个对象作为响应。

因此,使用.where()可以使用take或.where(...).first -or- .take -or- [0]

使用.find(params[:id]) ,它会更简洁一些,只返回您要查找的记录,否则返回错误。 .where()如果找不到您要寻找的内容,则不会出错。 这是要记住的其他事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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