2011-02-13 60 views
1

現在我的帖子模型的has_many:標籤:通過=>:tag_joins創建自動加入表記錄,軌道3

當我添加標籤,同時創造一個帖子,tag_join記錄被自動創建。

現在,我試圖完成:在查看帖子的顯示視圖時,我希望能夠添加新的標籤。

我試圖@ post.tag = Tag.new沒有工作(返回標籤的「nomethoderror」 =)

所以我試圖找出如何添加標籤,仍然創造那些加入自動。

我使用accepts_nested_attributes等

更新:我原來問如何做到這一點的索引視圖,但我已經改成了放映視圖 - 因爲我希望它是一個更容易一些。

回答

1

您與@posts.tags = Tag.new的距離不會太遠。這裏有幾種方法可以做到這一點;

@post.tags << Tag.create(params[:tag]) 
@post.tags.create params[:tag] 

我看到一對夫婦的方法這個問題..一種是通過崗位與使用一個hidden_field標籤形式的ID或通過使用嵌套的路線標籤。然後,您可以在控制器中使用它來檢索帖子並使用與上述類似的語法。

雖然這可行,但問題在於它有點難看。它意味着您的標籤控制器會處理查找帖子(這不一定是錯誤的,但它不應該擔心帖子。除非標籤只能與帖子相關聯,這是)。

處理它的更優雅的方式是使您顯示的窗體成爲帖子實例的窗體,而不是標籤。然後,您可以使用nested attributes將標記創建爲帖子的一部分。

+0

沒有@post VAR不過,我應該創建一個? – Elliot 2011-02-13 15:19:21

0

看看關聯(belongs_to,has_many等)add to the models的build_xxx或create_xxx方法。你需要通過rails的帖子創建你的標籤來自動「連接」它。

0

這裏的關鍵觀察是.new和.create之間的區別。對於我的Devour.space應用程序,我遇到了同樣的問題。如果在內存中使用以下內容創建對象:

tag = @post.tags.new(tag_params) 
tag.save 

將不存在保存到數據庫的tag_joins條目。 @ post.tags不會返回你的新標籤。您必須在實例化的時刻使用.create或協會將不被記錄在JOIN表:

tag = @post.tags.create(tag_params) 
@post.tags.last # tag 

在我的情況,這需要我如何創建行動處理的請求和錯誤的改變:

has_many :deck_shares 
has_many :decks, through: :deck_shares 
.... 

deck = current_user.decks.new(deck_params) 
if deck.save # Does not create entry in DeckShares table 
    render json: deck 
else 
    render json: deck.errors, as: :unprocessable_entity 
end 

這成爲:

begin 
    deck = current_user.decks.create(deck_params) # creates DeckShare 
rescue Exception => e 
    render json: e, as: :unprocessable_entity 
end 
render json: deck unless e