現在 3 つのモデルがあり、モデルの 1 つ (webpage.id) の参照を別のモデル (Micropost) に取り込もうとしています。状況は次のとおりです。
class Member < ActiveRecord::Base
has_many :microposts
end
class Webpage < ActiveRecord::Base
has_many :microposts, :dependent => :destroy
end
class Micropost < ActiveRecord::Base
belongs_to :member
belongs_to :webpage
end
私がやろうとしているのは、ウェブページの ':show' メソッドからマイクロポストを作成することです。
マイクロポスト コントローラーは次のとおりです。
class MicropostsController < ApplicationController
def create
@micropost = current_member.microposts.build(params[:micropost])
@webpage = Webpage.find(params['webpage_id'])
@micropost.webpage = @webpage
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_path
else
@feed_items = []
render 'pages/home'
end
end
end
Web ページの「表示」ビューから:
<table class="front" summary="For signed-in members">
<tr>
<td class="main">
<h1 class="micropost">What's up?</h1>
<%= form_for @micropost do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.text_area :content %>
<input type="hidden" id="webpage_id" name="micropost[webpage_id]" value="<%= @webpage.id %>"/>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
</td>
</tr>
</table>
フォームを保存すると、次のエラーが表示されます。
「ID のない Web ページが見つかりませんでした」
フォームから Webpage への参照を削除すると、フォームは user_id フィールドを正常に保存して設定するため、これは正常に機能しています (ただし、この場合、明らかに webpage_id は NULL です)。
私が間違っているところについて何か考えはありますか?
乾杯、
ダモ