form_for を構築して、他の 2 つのモデル間の結合モデルを作成しようとしています。Book モデルと User モデルがあり、Reads という別のモデルが結合されています。関連付けを設定した方法は次のとおりです。
class User < ActiveRecord::Base
has_many :reads
has_many :books, :through => :reads
end
class Book < ActiveRecord::Base
has_many :reads
has_many :users, :through => :reads
end
class Read < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
form_for のドキュメントを見て、多対多の関連付けに関する Railscast のエピソードを見ましたが、Book#show ビューを表示しようとするとエラーが発生する理由がわかりません。フォームを入れます:
First argument in form cannot contain nil or be empty
app/views/books/show.html.erb の私のフォームは次のとおりです。
<%= form_for(@read) do |f| %>
<%= f.hidden_field :book_id, value: @book.id %>
<%= button_to 'Add to Reads', {controller: 'reads', action: 'create'}, {class: 'btn'} %>
<% end %>
問題の一部は、Books モデルから「Reads」オブジェクトを作成しようとしていることにあると思いますが、何が間違っているのかわかりません。ユーザーが特定の本を選択して「読み物」に追加できるように、本のページに「読み物に追加」ボタンが必要です。また、ビューではなくコントローラーに current_user id を追加しています。それが役立つ場合は、読み取りコントローラーからの作成アクションを次に示します...
def create
@read = Read.new(read_params)
@read.user_id = current_user.id
@read.save
if @read.save
# do this
else
# do that
end
end
そして、私は強力なパラメータを使用しています...
def read_params
params.require(:read).permit(:user_id, :book_id)
end
助けてくれてありがとう。