ユーザーモデルと本モデルがあります。ユーザーは、Readingsモデルにエントリを作成する本を(リーダーとして)読むことができます。
id | reader_id | book_id
ユーザーは、読んだ本のリストも持っています。これらは、上記のリーディングモデルと同じように見える赤(「読む」という単語の現在形と過去形が同じであるため、赤を使用します)モデルに保存されます。
ユーザーが本を読んでいるときに、本を読み終えたことを表すボタンを表示したいと思います。
終了アクションは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 %>
しかし、何らかの理由で、「9781440506604」は読み取りテーブルのレコードのIDではなく、本のテーブルのレコードのID(正確には本のISBN-13)であるため、間違ったIDのフォームがレンダリングされます。 。
<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