Ruby on Rails 模型关系
需要一些建议。 我正在做一个关于 RoR 的项目,不确定应该使用模型之间的关系。我有三个模型 - 用户、论坛和消息。 开头非常简单: 用户有一面墙,它属于用户,所以我想这应该是:
class User < ActiveRecord::Base
has_one :board
end
class Board < ActiveRecord::Base
belongs_to :user
end
最后一个模型是消息,这就是我的问题。消息属于用户,因为他写了它,但它也属于墙,因为他把它写在墙上(并且它可以是属于其他用户的墙)。
我使用了简单的解决方案:
class Theme < ActiveRecord::Base
belongs_to :board
belongs_to :user
end
class User < ActiveRecord::Base
has_one :board
has_many :themes
end
class Board < ActiveRecord::Base
belongs_to :user
has_many :themes
end
但我对它不满意,觉得它不完美。我正在寻找一个解决方案,让我可以这样写:(
user.themes.create(:board => @board)
现在它不填充 user_id 字段)
我希望对于那些在 Ruby on Rails 模型方面比我更有经验的人来说这不是一项艰巨的任务。我会很感激好的建议,谢谢。
need some advice.
I'm doing a project on RoR, and do not sure what relationship between the models should I use. I've got three models - Users, Boards and Messages.
The beginning is pretty simple:
User has one Wall, and it belongs to the User, so I guess this should be:
class User < ActiveRecord::Base
has_one :board
end
class Board < ActiveRecord::Base
belongs_to :user
end
The last model is Messages and here comes my problem. Message belongs to User cause he writes it, but it also belongs to a Wall cause he writes it on a wall (and it can be Wall that belongs to other user).
I used the simple solution:
class Theme < ActiveRecord::Base
belongs_to :board
belongs_to :user
end
class User < ActiveRecord::Base
has_one :board
has_many :themes
end
class Board < ActiveRecord::Base
belongs_to :user
has_many :themes
end
But I not satisfy with it, and feel that it isn't perfect. I'm looking for a solution that will let me write thinks like:
user.themes.create(:board => @board)
(now it doesn't fill user_id field)
I hope that isn't a hard task for those who more experienced than me in Ruby on Rails model. I'll appreciate good advices, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般情况下,您可以使用一些诸如认证宝石之类的设备。然后您就有了 current_user 变量,其中包含当前正在调用该操作的用户的对象。
然后,当用户创建主题时,您可以向控制器添加一行简单的行来设置用户:
您还应该使用像 cancan 这样的 gem 来管理中央文件中的授权。您可以在这里找到railscast:
http://railscasts.com/episodes/192-authorization-with -康康舞
For normal you use some authentification gem like devise. Then you have the current_user variable which includes the object of the user that is currently calling the action.
Then when a user creates the Topic you add one simple line to the controller to set the user:
You should also use a gem like cancan to manage the authorisation in a cenral file. Youl find a railscast here:
http://railscasts.com/episodes/192-authorization-with-cancan