activerecord - Undefined method error when using "has_many :through" relationship on Rails3 -
i working on small android project ror server. here 3 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 |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 |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 |t| t.integer :user_id t.integer :friend_id t.timestamps end end
model user uses model relation connect model friend. use scaffold creat 3 models , add relationship code in model files. create api controller send xml file android application. here controller code:
def find_friend @user=user.where("id=?",params[:id]) @friend=@user.friends respond_to |format| format.html format.xml end end
here problem, when use api(type in http://localhost:3000/api/find_friend/1.xml), server throws mistake:
nomethoderror in apicontroller#find_friend undefined method `friends' #<activerecord::relation:0x3478a28> app/controllers/api_controller.rb:21:in `find_friend' i new rails , have no idea wrong is. have add in "route.rb" or change migration file?
in rails console mode, type in "user=user.find(1), friend=user.friends" , correct result.
~~~~(>_<)~~~~ problem controller method "@user=user.where("id=?",params[:id])". "where" method can not tell whether result array or 1 object. if use "@user=user.find(params[:id])", rails "smart enough" know "oh, yes, 1 object , has method called friends because connects 2 models together". learning rails likes marriage, think know think "god know nothing mysterious guy."
Comments
Post a Comment