我有一个用户模型和一个书籍模型。用户可以阅读书籍(如,读取器),其会在阅读模式的条目:此表单路由有什么问题?
id | reader_id | book_id
用户也有他们已阅读书籍的列表。这些存储在红色(我使用红色,因为'read'这个词的现在和过去时是相同的)模型,它看起来与上面的Reading模型相同。
现在,当用户正在阅读一本书时,我想显示一个代表完成本书的按钮。
的完成动作是在ReadingsController,看起来像这样:
def finish
@book = current_user.readings.find(params[:id]).book
current_user.stop_reading!(@book)
current_user.make_red! @book
redirect_to :back
end
正如你可能会说,这需要在读数表中的记录的ID,破坏它,使一个新的记录记录书籍的表格为红色。
为“读完”按钮时,表单助手目前看起来是这样的:
<%= form_for :reading, current_user.readings.find_by_book_id(book.id), :url => { :controller => :readings, :action => "finish" }, :method => :delete do |f| %>
<div class="actions"><%= f.submit button_text %></div>
<% end %>
但出于某种原因,这使得用错误ID的形式,因为“9781440506604”不是记录在id在阅读表中,它是书籍表中的记录的标识(准确地说,书的ISBN-13)。
<form accept-charset="UTF-8" action="/readings/9781440506604/finish" method="post">
</form>
这是什么我做错了?
编辑添加reading.rb
class Reading < ActiveRecord::Base
attr_accessible :book_id
# one person reading a new book may cause feed_item creations in multiple users feeds
has_many :feed_items, :as => :event
has_many :comments, :as => :parent, :dependent => :destroy
scope :from_users_followed_by, lambda { |user| followed_by(user) }
# need to pass the class name here because there is no Reader model
belongs_to :reader, :class_name => "User"
belongs_to :book
validates :reader_id, :presence => true
validates :book_id, :presence => true
def self.followed_by(user)
...
end
end
# and user.rb
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation, :avatar, :remember_me, :avatar_url
has_many :readings, :dependent => :destroy,
:foreign_key => "reader_id"
has_many :reads, :through => :readings, :source => :book
has_many :reds, :foreign_key => "reader_id",
:dependent => :destroy
has_many :red, :through => :reds, :source => :book
def reading? book
self.readings.find_by_book_id(book)
end
def read! book
self.readings.create!(:book_id => book.id)
end
def stop_reading! book
self.readings.find_by_book_id(book).destroy
end
def red? book
self.reds.find_by_book_id(book)
end
def make_red! book
unless red? book
self.reds.create!(:book_id => book.id)
end
end
end
通过我试图使谁在看书1,做user.readings.find_by_book_id用户(1)在控制台,它返回一个记录的方式来自读数表。
的要求
# routes.rb
resources :readings, :only => [:create, :destroy, :show] do
member do
post :create_comment
delete :finish
end
end
显示您的阅读模型代码 – fl00r 2011-04-06 18:31:01
编辑的OP添加这个。 – 2011-04-06 19:03:14
和用户模型也会有用 – fl00r 2011-04-06 19:09:50