我目前有三个模型,并试图将其中一个模型(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'方法创建一个Micropost。
这是 Micropost 控制器:
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
并从网页“显示”视图:
<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 的网页”
当我从表单中删除对网页的引用时,表单成功保存并设置了 user_id 字段 - 所以这工作正常(但显然在这种情况下,webpage_id 为 NULL)。
关于我要去哪里错的任何想法?
干杯,
达摩