Rails - belongs_to, has_many
source link: https://www.codesd.com/item/rails-belongs-to-has-many.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Rails - belongs_to, has_many
I'm trying to setup a model relationship in rails and could use your help, as it's not working :0
class User < ActiveRecord::Base
has_many :request_threads
end
class RequestThread < ActiveRecord::Base
belongs_to :user, :foreign_key => :creator_id
end
In terms of schemas, the request_threads table has creator_id instead of user_id, maybe that's the issue?
I want to be able to do:
@user.request_threads
But this isn't working, errors. Ideas?
UPDATED
Error Message: "Started POST "/request_threads" for 127.0.0.1 at Wed Nov 10 22:21:41 -0800 2010 Processing by RequestThreadsController#create as JS Parameters: {"request_thread"=>{"request_type_id"=>"1", "message"=>"blahdiado"}, "authenticity_token"=>"o9ibF/m8Vw4Uce5u1n3R+atD2/XVqnZcBVOdXimAZEA=", "utf8"=>"✓", "recipients"=>["4", "3"]} User Load (0.7ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 2) LIMIT 1 CACHE (0.0ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 2) LIMIT 1 Completed in 63ms
NoMethodError (undefined method user_id=' for #<RequestThread:0x1058df0d0>): app/controllers/request_threads_controller.rb:50:in
create' app/middleware/flash_session_cookie_middleware.rb:14:in `call' "
Try this out.
class User < ActiveRecord::Base
has_many :request_threads, :foreign_key => :creator_id
end
class RequestThread < ActiveRecord::Base
belongs_to :user
end
Controller looks ok. Ok try this out in your RequestThread model.
alias_attribute :user_id, :creator_id
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK