Active Record Rspec查询接口错误

时间:2014-11-18 08:55:09

标签: ruby-on-rails activerecord rspec

我正在使用Rails的API,并且一直在摸索如何为我的Get路由设置关联,规范和控制器。目标 - 作为用户,我想获得最接近我的位置的所有未被查看的笔记。我知道被查看了吗?逻辑关闭,收件人模型和Nearests控制器中的查询接口也是如此。

这是Error Rspec给我的错误:

  Failure/Error: note1 = create(:note)
   NoMethodError:
     undefined method `recipient_id=' for #<Note:0x007fd2a40e1400>

这是规范:

describe 'GET /v1/notes/nearests?lat=&lon=&radius=' do
  it 'returns the notes within the given radius' do
    near_note1 = create(:note, lat: 37.760322, lon: -122.429667)
    near_note2 = create(:note, lat: 37.760322, lon: -122.429667)
    lat = 37.771098
    lon = -122.430782
    radius = 10 

    get "/v1/notes/nearests?lat=#{lat}&lon=#{lon}&radius=#{radius}"

    expect(response_json).to eq([
      {
        'id' => [near_note1.id, near.note2.id],
        # 'lat' => near_note1.lat,
        # 'lon' => near_note1.lon,
        'note_text' => [near_note1.note_text, near_note2.note_text],
        'photo_uri' => [near_note1.photo_uri, near_note2.photo.uri],
        # 'expiration' => near_note.expiration.as_json,
        'viewed'  => [near_note1.viewed?, near_note2.viewed?]
      },
    ])
  end
end

这是控制器代码:

def index
  @notes = Note.near([
    params[:recipient_id],
    params[:lat], 
    params[:lon]],
    radius: :APP_CONFIG['radius'], 
    units: :APP_CONFIG['units']
  )
end

以下是工厂 - 注释

FactoryGirl.define do
  factory :note do |u|
    sender_id {FactoryGirl.create(:user).id}
    recipient_id {FactoryGirl.create(:user).id}
    lat 1.5
    lon 1.5
    note_text "MyString"
    photo_uri "MyString"
    expiration Time.zone.now.utc
  end
end

我的模特:

用户模型

class User < ActiveRecord::Base
  has_many :notes

  validates :first_name, :last_name, :pw, presence: true
  validates :email, :username, :devicetoken, presence: true, uniqueness: true
  validates :email, length: { minimum: 8 }
end

注意模型

class Note < ActiveRecord::Base
  belongs_to :user, foreign_key: 'sender_id', class_name: 'User'
  has_many :recipients, foreign_key: 'recipient_id', class_name: 'User'

  validates :sender_id, presence: true
  validates :lat, presence: true 
  validates :lon, presence: true
  validates :note_text, presence:true 
  validates :expiration, presence: true
  reverse_geocoded_by :lat, :lon

end

收件人模型

class Recipient < ActiveRecord::Base
  belongs_to :note, foreign_key: 'recipient_id', class_name: 'Note'

  def get_recipient
    Note.find(:all, params[:note_id])
  end


  def viewed?
  end 
end

0 个答案:

没有答案