如何向用户和用户添加书籍?

时间:2011-11-13 23:29:14

标签: ruby-on-rails mongoid has-and-belongs-to-many

我有两个实体,即具有has_and_belongs_to_many关系的用户和图书。如何在Book#Show视图中有一个按钮,当单击时将用户添加到Book.user_ids []并将书籍添加到User.book_ids []?

1 个答案:

答案 0 :(得分:2)

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

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

/books/:id

路线看起来像:

namespace :assignments do
  resources  :books, :only => [:show] do
    resources  :users, :only => [:update]
  end
end
然后show节目将是:

# /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 %>
相关问题