我正在构建一个RoR应用,用户可以点击图书类别将书籍列表添加到他们的个人资料中。我对这些东西有点新意,我现在对于下一步该去哪里感到有些困惑。
型号:
我有几千种不同类别的书。单击某个类别后,我希望将该类别的书籍添加到用户的个人资料页面。
这是我到目前为止所做的:
book.rb
class Book < ActiveRecord::Base
has_many :book_lists
has_many :users, :through => :book_lists
end
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :book_lists
has_many :books, :through => :book_lists
end
book_list.rb
class BookList < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
devise_create_users.rb迁移
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
# i only included relevant to the question stuff here.
# Standard Devise stuff taken out.
t.integer :user_id
图书迁移
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.string :category
t.string :title
t.integer :book_id
t.timestamps
end
end
end
book_list迁移
class CreateBookLists < ActiveRecord::Migration
def change
create_table :book_lists do |t|
t.timestamps
end
end
end
book_list_controller.rb
class BookListController < ApplicationController
def save_book
@saved_book = BookList.new(params[:saved_book]
@saved_book.user = current_user
@saved_book.save
end
end
图书清单视图
<%= form_for BookList.new, :url => "/books/save_book" do |f| %>
<%= f.hidden_field :book_id, :value => @book_id %>
<%= f.submit "Save Books" %>
<% end %>
我应该添加什么才能让图书根据图书类别保存到用户的个人资料页面?
很抱歉,如果上述代码无论如何都是荒谬的。我从各个论坛拼凑起来。
编辑:
CodeApp::Application.routes.draw do
devise_for :users, path_names: {sign_in: 'login', sign_out: 'logout'}
get "profile", to: "profile#show"
resources :books
root "books#welcome"
get "search", to: "search#index"
get "about", to: "books#about"
get "books", to: "books#index"
post "save_book", to: "book_list#save_book"
答案 0 :(得分:1)
此代码
<%= form_for BookList.new, :url => "/books/save_book" do |f| %>
应该是
<%= form_for @saved_book, :url => "/books/save_book" do |f| %>