Rails - 使用属性连接表(HABTM + Through)但是如何创建/删除记录?
我有一个用户模型和兴趣模型,通过名为“选择”的连接表连接(详细信息如下)。我正在使用 HABTM 与 through 关系,因为我在连接表中也有一个属性。
User.rb
has_many :choices
has_many :interests, :through => :choices
Interest.rb
has_many :choices
has_many :users, :through => :choices
Choice.rb
belongs_to :user
belongs_to :interest
所以问题是如何将记录添加到这个新创建的选择表中。例如=>
@user = User.find(1)
@interest = Interest.find(1)
????? Choice << user.id + interest.id + 4(score attribute) ??????
最后一部分是我遇到问题的部分..我有这 3 个参数,但不知道如何添加它们以及语法是什么?
I have a User model and Interest Model being joined by a join table called Choice (details below). I'm using the HABTM relationship with through since I have an attribute within the join table as well.
User.rb
has_many :choices
has_many :interests, :through => :choices
Interest.rb
has_many :choices
has_many :users, :through => :choices
Choice.rb
belongs_to :user
belongs_to :interest
So the question is how do I add records to this newly created choice table. For example =>
@user = User.find(1)
@interest = Interest.find(1)
????? Choice << user.id + interest.id + 4(score attribute) ??????
The last part is the part I'm having a problem with..I have these 3 parameters and didn't how to add them in and what the syntax was?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有几个选项来添加选项,但最有意义的可能是通过将范围限定到用户实例来添加选项:
假设:
您可以像这样添加选项:
您也可以在控制器中执行类似的操作:
这假设您的表单具有
choice[:interest_id]
和choice[:score]
字段You have a couple options for adding a choice, but what probably makes the most sense would be to add choices by scoping to the user instance:
Assuming:
You could add a choice like so:
You could also do something like this in your controller:
This assumes your form has fields for
choice[:interest_id]
andchoice[:score]