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 %>
发布评论
评论(1)
首先,停止使用 has_and_belongs_to_many。使用 has_many :through。如果您想要连接表上的属性,那就更好了。
其次,我会添加一个像这样的控制器。
路线将如下所示:
那么显示操作将是:
update_action 将位于 /users_controller.rb
现在位于 models/book.rb
最后在视图中:
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.
routes would look like:
then the show action would be:
the update_action would be in the /users_controller.rb
Now in models/book.rb
Finally in the view: