Rails - 使用属性连接表(HABTM + Through)但是如何创建/删除记录?

发布于 2024-10-10 22:17:01 字数 622 浏览 7 评论 0原文

我有一个用户模型和兴趣模型,通过名为“选择”的连接表连接(详细信息如下)。我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萤火眠眠 2024-10-17 22:17:01

您有几个选项来添加选项,但最有意义的可能是通过将范围限定到用户实例来添加选项:

假设:

@user = User.find(1)
@interest = Interest.find(1)

您可以像这样添加选项:

@user.choices.create(:interest => @interest, :score => 4)

您也可以在控制器中执行类似的操作:

def create
  @choice = @user.choices.build(params[:choice])

  if @choice.save
    # saved
  else
    # not saved
  end
end

这假设您的表单具有 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:

@user = User.find(1)
@interest = Interest.find(1)

You could add a choice like so:

@user.choices.create(:interest => @interest, :score => 4)

You could also do something like this in your controller:

def create
  @choice = @user.choices.build(params[:choice])

  if @choice.save
    # saved
  else
    # not saved
  end
end

This assumes your form has fields for choice[:interest_id] and choice[:score]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文