NoMethodError when I try to acces a field of an object taken from the DB

前端 未结 4 1664
[愿得一人]
[愿得一人] 2021-01-25 20:19

  Let\'s say that I have a model called Tweet with the following fields

  • 1. id
  • 2. content
  • 3. created_at
  • 4. user_id
  • <
相关标签:
4条回答
  • 2021-01-25 20:47

    In your case, It returns a collection of object of Active Record Relation

    so for specific record

    @original.first.id gives you 64

    or

      @tweet = Tweet.find(64)
      @tweet.id #64
      @tweet.content # "Unde et nisi blanditiis vel occaecati soluta praes..."
    
    0 讨论(0)
  • 2021-01-25 20:49

    It's because where returns a collection not a single object

    So instead of

    @tweet = Tweet.where(id: 64)
    

    You want

    @tweet = Tweet.find(64)
    

    because you're using the id

    0 讨论(0)
  • 2021-01-25 20:50

    @original is not a Tweet instance but an ActiveRecord::Relation

    If you want to access the id of your Tweet directly you should define @original like this

    @original = Tweet.find_by_id(64)
    

    or

    @original = Tweet.where(id: 64).first
    
    0 讨论(0)
  • 2021-01-25 20:54

    Do this instead, you need to add first

    @tweet = Tweet.where(id: 64).first
    
    0 讨论(0)
提交回复
热议问题