gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中使用多对多?

转载 作者:行者123 更新时间:2023-12-04 06:52:08 25 4
gpt4 key购买 nike

在我的项目中,我有用户和任务。一个用户可以加入多个任务,一个任务可以有多个用户。
所以我创建了一个名为 questing 的表,其中包含 user_id 和 quest_id。
在我的 user.rb 中,我执行了以下操作:

require 'digest/sha1'
class User < ActiveRecord::Base
has_many :questings
has_many :quests ,:through =>:questings
...

我的任务.rb:
class Quest < ActiveRecord::Base
has_many :questings
has_many :users ,:through =>:questings
...

我的 Questing.rb:
class Questing < ActiveRecord::Base
belongs_to :quest
belongs_to :user
end

现在我想在我的/quests/show.html.erb 上创建一个链接或按钮,在我的 Controller 中调用一个 Action ,这将创建用户和任务之间的关系。

所以,在我的 quest_controller 我做了:
  def join_quest
@quest = Quest.find(params[:id])
puts '************************'
puts 'join quest:' + @quest.id
puts '************************'
respond_to do |format|
format.html { redirect_to(@quest) }
format.xml { head :ok }
end
end

在我的 show.html.erb 中我做了:
<%= link_to 'join this quest!!!', :action => :join_quest %>

现在,单击此链接将导致错误,例如: Couldn't find Quest with ID=join_quest并且 url 指向/quests/join_quest 而不是/quests/1/join_quest

现在我的问题:

我的 quests_controller 是否适合我的 join_quest 操作,还是应该将其移至我的 users_controller?

为什么我会收到这个错误?如何解决?

为了保存关系,我必须在 join_quest 操作中写什么?

在我的/users/show.html.erb 上,我想输出用户加入的所有任务。这该怎么做?我必须从我的关系表中获得所有这些任务,对吗?如何?

我希望你可以帮助我!谢谢!

编辑:
添加时 :member=>{:join_quest=>:get}到我的 routes.rb ( map.resources :quests, :member=>{:join_quest=>:get} ) 它将调用/quests/1/join_quest 并以正确的方式调用我的操作。
但是我仍然不知道在我的操作中写什么来保存连接。

最佳答案

为了保存关系,你需要类似的东西

# quests controller
@quest.questings.create(:user_id => current_user)

但我假设您可以获得 current_user .

希望能帮助到你...

编辑

回答您的问题:

Is my quests_controller the right place for my join_quest action, or should I move it to my users_controller?



您可以在 users 中执行此操作和 quests controller ,无论在何处都对您更有效。

What do I have to write in my join_quest action for saving the relationship?



以上回答。

On my /users/show.html.erb I want to output all quests the user joined. How to do this? I have to get all this quests from my relationship table, right? How?


# users controller, show method
@user = User.find(params[:id], :include => :quests)

# show view
<% @user.quests.each do |quest| %>
# print whatever you want from the quest
<%= quest.any_attribute %>
<% end %>

关于ruby-on-rails - 如何在 Rails 中使用多对多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2957141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com