简体   繁体   English

我可以使用Model.find(params [:id])。where()之类的东西吗

[英]ruby on rails can i use something like Model.find(params[:id]).where()

Hi, I am still a student and I'm taking a software engineering course and we have this big project (web design) and we're using rails so my question is I have a table Users and a table Groups and another association table GroupUsers where it has two foreign keys user_id and group_id . 嗨,我还是学生,我正在上软件工程课程,我们有这个大项目(网页设计),而且我们使用的是Rails,所以我的问题是我有一个表Users和一个表Groups和另一个关联表GroupUsers它有两个外键user_idgroup_id Whenever a user creates or join an already created group his id and the group_id are added to GroupUsers table 每当用户创建或加入已创建的组时,其ID和group_id都会添加到GroupUsers表中

module GroupUsersHelper
   def join
      @group_id = params[:id]
      @user_id = params[:user_id]
      @newuser= GroupUser.new(:group_id => @group_id, :user_id => @user_id)
      @newuser.save
      redirect_to(:controller => 'groups', :action => 'show', :id => @group_id)
   end
end

Now I have to create method leave group where I'll have to destroy the record from GroupUsers , so I wrote this code also in GroupUsersHelper 现在我必须创建方法离开组,在这里我必须销毁来自GroupUsers的记录,因此我也在GroupUsersHelper编写了此代码

  def leave
      @group_id = params[:group_id]
      @user_id = params[:user_id]
      @group_user_id = params[:group_user_id]
      @newuser= GroupUser.find(@group_user_id).where(:group_id => @group_id, :user_id =>
      @user_id)
      @newuser.destroy
      redirect_to(:controller => 'groups', :action => 'show', :id => params[:id])
   end

but I get this error 但是我得到这个错误

ActiveRecord::RecordNotFound in GroupsController#leave

Couldn't find GroupUser without an ID 没有ID找不到GroupUser

If you need more info about the code please let me know. 如果您需要有关代码的更多信息,请告诉我。

Model.find(params[:id]) will generate such kind of query

 *Lets take an example : GroupUser.find(params[:id]) will generate sql equivalent*
 select * from group_users where id = params[:id]

If you want to add where condition do something like this
GroupUser.where("# id ={params[:id]} and someColumn = #{somevariable}")

You are not passing the groupuser_id in the params hash. 您没有在params哈希中传递groupuser_id Instead of storing it in the @group_id and @user_id , just try this: 不用将其存储在@group_id@user_id ,只需尝试以下操作:

@newuser= GroupUser.find_by_group_id_and_user_id(params[:group_id],params[:user_id])

Can you additionally post your params dump so we can figure out how to make a good redirect since i hence that will be a problem also. 您能否另外发布您的params dump,以便我们找出如何进行良好的重定向,因为我因此也将成为问题。

Just do: 做就是了:

group = Group.find(params[:group_id])
user = User.find(params[:user_id])
group.users.delete(user)
group.save

This will remove the user from the users association, and will automatically destroy the GroupUser record when the group is saved. 这会将用户从用户关联中删除,并在保存组时自动销毁GroupUser记录。 See the collection.delete method. 请参见collection.delete方法。

The other answers addressed your code example, but not the question in the title. 其他答案解决了您的代码示例,但没有解决标题中的问题。 You cannot use Model.find(params[:id]).where() in ActiveRecord (Rails' default ORM). 您不能在ActiveRecord(Rails的默认ORM)中使用Model.find(params[:id]).where() )。 Model.find returns a single record (an instance of your Model class) but Model.where returns a Model::ActiveRecord_Relation object (an array-like object). Model.find返回单个记录(您的Model类的实例),但是Model.where返回一个Model :: ActiveRecord_Relation对象(类似于数组的对象)。 The .where method is only available on your Model class directly (ie Model.where ) or on an ActiveRecord_Relation. .where方法仅可直接用于您的Model类(即Model.where )或ActiveRecord_Relation。 If you are chaining methods, you need to make sure each method returns an ActiveRecord_Relation. 如果要链接方法,则需要确保每个方法都返回一个ActiveRecord_Relation。 For example: 例如:

Model.where("name = ?", "max")
     .order(created_at: :desc)
     .reorder(created_at: :asc)
     .includes(:sent_comments)

@max pleaner is right, you should not use Model.find().where(). @max pleaner是正确的,您不应使用Model.find()。where()。

It is incorrect, and if you think about it, you will see that it is redundant. 这是不正确的,如果您考虑一下,您会发现它是多余的。 To find the association you wish to destroy, you either need params[:group_id] and params[:user_id], or just params[:group_user_id]. 要找到您想要破坏的关联,您需要params [:group_id]和params [:user_id],或者只是params [:group_user_id]。

If you have passed the params[:group_user_id] to the leave method, you already have all the information needed to find the association: 如果您已将params [:group_user_id]传递给Leave方法,则您已经具有查找关联所需的所有信息:

def leave
  @newuser= GroupUser.find(params[:group_user_id])
  @newuser.destroy
  redirect_to(:controller => 'groups', :action => 'show', :id => params[:group_id])
end

Or alternatively, If you have passed the params[:group_id] and params[:user_id] to the leave method: 或者,如果您已经将params [:group_id]和params [:user_id]传递给了离开方法:

def leave
  @newuser= GroupUser.find_by_group_id_and_user_id(params[:group_id], params[:user_id])
  @newuser.destroy
  redirect_to(:controller => 'groups', :action => 'show', :id => params[:group_id])
end

Also, there are a few other redundancies in your code that you will notice I omitted above. 另外,您的代码中还有一些其他冗余,您会注意到上面我省略了。 There is no need to assign each parameter to an instance variable before passing the parameter to the find() method: 在将参数传递给find()方法之前,无需将每个参数分配给实例变量:

@model_id = params[:model_id]
@model= Model.find(@model_id)

#can be simplified to:

@model = Model.find(params[:model_id])

Generally, you only want to create instances variables for a record or collection of records you will need to access in a view (such as a Group in the context of your application). 通常,您只想为视图中需要访问的记录或记录集合创建实例变量(例如,应用程序上下文中的Group)。

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

相关问题 Ruby on Rails:将 model.find(params[:id]) 保存到类变量后,显示操作出现问题 - Ruby on Rails: After saving model.find(params[:id]) into class variable, something is going wrong in show action Rails:Model.find()或Model.find_by_id()以避免RecordNotFound - Rails: Model.find() or Model.find_by_id() to avoid RecordNotFound ruby-on-rails检查查询结果是否为空(Model.find) - ruby-on-rails check if query result is empty (Model.find) ruby on rails更改Model.find()的默认列 - ruby on rails change default column on Model.find() Ruby on Rails Model.find():两个查询而不是子查询 - Ruby on Rails Model.find(): Two Queries instead of Subquery Model.all和Model.find(id):我可以使用一个查询来做到这一点吗? - Model.all and Model.find(id): can I do this with one query? 如何在 rails 2.3.x 中执行 Model.find(:except => 'desc') ? - How can I do Model.find(:except => 'desc') in rails 2.3.x? Sqlite Rails外键:我可以在Rails的哪里写类似FOREIGN KEY(User_id)的参考User(id) - Sqlite Rails foreign key : where in rails can i write something like FOREIGN KEY(User_id) REFERENCES User(id) Model.find返回具有错误ID的对象 - Model.find returns object with wrong ID 什么是Ruby on Rails(Mongoid)中object.models.find()与Model.find()的成本/收益 - What is cost/benefit of object.models.find() vs Model.find() in Ruby on Rails (Mongoid)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM