Samson
Samson

Reputation: 39

Undefined method error when using "has_many :through" relationship on Rails3

I am working on a small Android project with RoR server. Here are the three models:

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

end

def self.down
  drop_table :users
end

end

 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

end

  class CreateRelations < ActiveRecord::Migration
def self.up
create_table :relations do |t|
  t.integer :user_id
  t.integer :friend_id
  t.timestamps
end

end

Model User uses model Relation to connect with model Friend. I use scaffold to creat the three models and add the relationship code in their model files. I also create a API controller to send xml file to Android application. Here is the controller code:

def find_friend
  @user=User.where("id=?",params[:id])
  @[email protected]
respond_to do |format|
  format.html
  format.xml
end

end

Here is the problem, when I use the api(type in http://localhost:3000/api/find_friend/1.xml), the server throws a mistake:

NoMethodError in ApiController#find_friend

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

I am new to Rails and have no idea where the wrong is. Do I have to add something in the "route.rb" or change the migration file?

In the rails console mode, I type in "user=User.find(1), friend=user.friends" and get the correct result.

Upvotes: 1

Views: 1917

Answers (1)

Samson
Samson

Reputation: 39

~~~~(>_<)~~~~ The problem is the controller method "@user=User.where("id=?",params[:id])". The "where" method can not tell whether the result is an array or actually one object. If I use "@user=User.find(params[:id])", rails will be "smart enough" to know that "Oh, yes, this is just one object and it has a method called Friends because someone connects the two models together". Learning Rails likes a marriage, you think you know well about her but sometimes you think "God actually I know nothing about the mysterious guy."

Upvotes: 3

Related Questions