[RUBY] About ActiveRecord_Relation and Couldn't find Item without an ID error

First, what is ActiveRecord_Relation :?

For example with a controller


def index
  User.all
end

When defined as This is what you brought with Use.all. At this time, all brings only record and column information.

What is Couldn't find Item without an ID?

In summary, I can't get the ID. means

For example with a controller


def index
  User.find(params[:id])
end

Suppose you define

At this time, the [: id] part of params cannot be obtained. It means that.

Status

――When do you get such an error?

That's when you're nesting in routing and trying to get information from a parent.

It is obvious if you check the table with Sequel Pro. Because the child element does not contain the information of the parent element.

At this time, you can see the meaning of the description that all is taken from records and columns.

solution

--Let's specify the id that will be the parent element after params



parent.find(params(:parent_id)

In particular

If you have a nest of users for parents and comments for children

comments to controller



@user = User.find(params(:user_id)

At the end

It took me a while to resolve this error, but it was simple to resolve. I understand that there are many things I still don't understand. There may be a possibility that you are writing something wrong because you are immature, something that is missing, or a typographical error. It's hard to read because it's my first post, but I'd like to end it with the hope of improving it little by little.

Recommended Posts

About ActiveRecord_Relation and Couldn't find Item without an ID error
What to do if you get the error Couldn't find Item without an ID
I got an error and couldn't push! !! [error: failed to push some refs to]
Find out about instance methods and self