Activerecord 使用“时出现未定义的方法错误”;有很多:通过;铁路上的关系3

Activerecord 使用“时出现未定义的方法错误”;有很多:通过;铁路上的关系3,activerecord,ruby-on-rails-3,Activerecord,Ruby On Rails 3,我正在使用RoR服务器进行一个小型Android项目。 以下是三种模型: class User < ActiveRecord::Base has_many :relations has_many :friends, :through => :relations attr_accessor :friend_ids end class Relation < ActiveRecord::Base belongs_to :user be

我正在使用RoR服务器进行一个小型Android项目。 以下是三种模型:

class User < ActiveRecord::Base
      has_many :relations
      has_many :friends, :through => :relations
      attr_accessor :friend_ids
end

class Relation < ActiveRecord::Base
   belongs_to :user
   belongs_to :friend
end

class Friend < ActiveRecord::Base
   has_many :relations
   has_many :users, :through => :relations
end


class CreateUsers < ActiveRecord::Migration
 def self.up
create_table :users do |t|
  t.string :user_name
  t.string :password
  t.integer :city_id
  t.integer :travelstyle_id
  t.boolean :online
  t.string :self_description
  t.string :sex
  t.integer :head_id

  t.timestamps
end
结束

结束

问题是,当我使用api(键入)时,服务器抛出一个错误:

NoMethodError in ApiController#find_friend

undefined method `friends' for #<ActiveRecord::Relation:0x3478a28>
app/controllers/api_controller.rb:21:in `find_friend'
ApiController中的命名错误#查找朋友 未定义的方法“friends”# app/controllers/api_controller.rb:21:in'find_friend' 我是Rails新手,不知道哪里出了问题。我是否必须在“route.rb”中添加一些内容或更改迁移文件

在rails控制台模式下,我输入“user=user.find(1),friend=user.friends”并得到正确的结果

_
 class CreateFriends < ActiveRecord::Migration
 def self.up
create_table :friends do |t|
  t.string :user_name
  t.integer :city_id
  t.integer :travelstyle_id
  t.string :self_description
  t.string :sex
  t.integer :head_id
  t.timestamps
end
  class CreateRelations < ActiveRecord::Migration
def self.up
create_table :relations do |t|
  t.integer :user_id
  t.integer :friend_id
  t.timestamps
end
def find_friend
  @user=User.where("id=?",params[:id])
  @friend=@user.friends
respond_to do |format|
  format.html
  format.xml
end
NoMethodError in ApiController#find_friend

undefined method `friends' for #<ActiveRecord::Relation:0x3478a28>
app/controllers/api_controller.rb:21:in `find_friend'