2011-03-28 47 views
2

我目前有三個模型,並試圖將其中一個模型(webpage.id)引用到另一個模型(Micropost)中 - 這裏是情況:Rails:在另一個模型的創建表單中捕獲模型ID

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。

這裏是微柱控制器:

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)。

對我要去的地方有何想法?

乾杯,

達摩

回答

0

轉儲PARAMS確保webpage_id是真正被傳遞。

在您的視圖中添加:

<%= debug params %> 
相關問題