2011-11-13 12 views

答えて

2

まず、has_and_belongs_to_manyの使用をやめてください。 has_many:throughを使用します。ジョイン・テーブルに属性が必要な場合は、さらに優れています。

第2に、私はこのようなコントローラを追加します。

/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 

になります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 

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