Trying to call find_by_id on ActiveRecord::Relation, Arel exception
I'm getting to grips wi开发者_如何转开发th Rails 3 and I can't seem to do a basic find from a result set. My code looks like the following:
@project =
@user.where({:projects => {:project_member_id => user.id}}).find_by_id(params[:id])
I understand that the "where" section will not return a collection but merely create a query that is waiting to be run against the db. However, I can't understand why I get the following error when I try to run the find_by_id:
undefined method `to_sql' for #<Arel::Attributes::String:0x106d9ecf0>
Can somebody point out where I'm going wrong please?
May be you can write something like this:
@project =
@user.where({:projects => {:project_member_id => user.id}}).where(:id => params[:id])
I think it will works.
Alex.
I could be misunderstanding what you are trying to do here, but it looks like you have an association called projects
in the user model, right? If so, this is much simpler (and works):
@project = @user.projects.find params[:id]
If you don't have an association setup, you should look into them. There is a great rails guide here on the subject.
I hope this helps.
As you mentioned above, "where" would return ActiveRecord::Relation object, you can check it by running:
@project =
@user.where({:projects => {:project_member_id => user.id}}).class
In order to return a collection of instantiated objects and run find, you can try to force it by running something like:
@project =
@user.where({:projects => {:project_member_id => user.id}}).all.find_by_id(params[:id])
Love method chaining in Rails!
However, this would first find all projects with passed uesr.id (which can be costly, and, probably not what you want)...
Good luck!
Try
@project =
@user.where({:projects => {:project_member_id => user.id}}).where(:id => params[:id]).first
But I dont understand why you are doing all these when you have the primary key with you..just Model.find params[:id]
is enough I think (I assume there is something more to it).
Try this:
@project = @user.where({:projects => {:project_member_id => user.id}}).all.find {|p| p.id == params[:id]}
精彩评论