Rails - belongs_to,has_many

时间:2010-11-11 06:15:53

标签: ruby-on-rails ruby-on-rails-3

我正在尝试在rails中设置模型关系并可以使用您的帮助,因为它不起作用:0

class User < ActiveRecord::Base
  has_many :request_threads
end

class RequestThread < ActiveRecord::Base
  belongs_to :user, :foreign_key => :creator_id
end

就模式而言,request_threads表有creator_id而不是user_id,这可能就是问题吗?

我希望能够做到:

@user.request_threads

但这不起作用,错误。想法?

已更新

错误消息:“已启动POST”/ request_threads“for 12月10日星期三22:21:41 -0800 2010   RequestThreadsController处理#create为JS   参数:{“request_thread”=&gt; {“request_type_id”=&gt;“1”,“message”=&gt;“blahdiado”},“authenticity_token”=&gt;“o9ibF / m8Vw4Uce5u1n3R + atD2 / XVqnZcBVOdXimAZEA =”,“utf8 “=&gt;”✓“,”收件人“=&gt; [”4“,”3“]}   用户负载(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 完成63毫秒

NoMethodError(未定义的方法user_id=' for #<RequestThread:0x1058df0d0>): app/controllers/request_threads_controller.rb:50:in创建'   app / middleware / flash_session_cookie_middleware.rb:14:在`call'中 “

2 个答案:

答案 0 :(得分:4)

试试这个。

class User < ActiveRecord::Base
  has_many :request_threads, :foreign_key => :creator_id
end

class RequestThread < ActiveRecord::Base
  belongs_to :user
end

控制器看起来不错。好的,在你的RequestThread模型中试试这个。

alias_attribute :user_id, :creator_id

答案 1 :(得分:2)

这应该适合你。

class User < ActiveRecord::Base
  has_many :request_threads, :foreign_key => :creator_id
end

class RequestThread < ActiveRecord::Base
  belongs_to :user, :foreign_key => :creator_id
end