如何将书籍添加到用户以及将用户添加到书籍?

发布于 2024-12-15 01:26:22 字数 1432 浏览 4 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

递刀给你 2024-12-22 01:26:22

首先,停止使用 has_and_belongs_to_many。使用 has_many :through。如果您想要连接表上的属性,那就更好了。

其次,我会添加一个像这样的控制器。

/books/:id

路线将如下所示:

namespace :assignments do
  resources  :books, :only => [:show] do
    resources  :users, :only => [:update]
  end
end

那么显示操作将是:

# /books/1
def show
  @book = Book.find(params[:id])
  @users = User.all # All is probably not what you want
end

update_action 将位于 /users_controller.rb

def update
  @book = Book.find(params[:book_id])
  @user = User.find(params[:id])
  @book.add_user(@user)
end

现在位于 models/book.rb

def add_user(@user)
  #  this is one of many things you could do...  This is not the best performance
  @book.user_ids = @book.user_ids << @user.id
  @book.save
end

最后在视图中:

 <% @users.each do |user| %>
   <%= link_to "Add #{user.name}", assignments_book_user_path(@book, user), :method => 'PUT' %>
 <% end %>

First, stop using has_and_belongs_to_many. Use has_many :through. Much better if and when you want an attribute on the join table.

Second, I would add have a controller like this.

/books/:id

routes would look like:

namespace :assignments do
  resources  :books, :only => [:show] do
    resources  :users, :only => [:update]
  end
end

then the show action would be:

# /books/1
def show
  @book = Book.find(params[:id])
  @users = User.all # All is probably not what you want
end

the update_action would be in the /users_controller.rb

def update
  @book = Book.find(params[:book_id])
  @user = User.find(params[:id])
  @book.add_user(@user)
end

Now in models/book.rb

def add_user(@user)
  #  this is one of many things you could do...  This is not the best performance
  @book.user_ids = @book.user_ids << @user.id
  @book.save
end

Finally in the view:

 <% @users.each do |user| %>
   <%= link_to "Add #{user.name}", assignments_book_user_path(@book, user), :method => 'PUT' %>
 <% end %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文