2011-08-08 27 views
0

我有我的應用程序一個Post模型,belongs_to一個User模型,以及一個Location模型。 UserLocation模型都使用has_manyPost的關係。Rails的要求:大專職位與用戶和位置

現在,在我的Post控制器的創建操作中,我想自動將Post與當前登錄的用戶(通過Devise爲current_user提供給我)關聯。

而且,它應該與關聯預先存在Location如果一個具有相同address場(他通過形式進入)是否存在,或者創建一個新的,如果不將其與關聯。

我的Post模型有一個user_id字段以及location_id字段爲此目的。

當用戶創建新帖子時,如何在創建操作中自動完成兩個關聯?

+0

問題是? – Dogbert

+0

@Dogbert更新。對不起,如果不明確。 –

+0

這是一個可以通過閱讀文檔很容易回答的問題。嘗試http://guides.rubyonrails.org/association_basics.html初學者。由於這一點,你不可能得到很好的答案,因爲看起來你沒有付出任何努力來自己解決。 – jergason

回答

1

您將需要使用2個語句。

@post = current_user.posts.build(params[:post]) 
@post.location_id = params[:location_id] # change this to whatever you're passing. 
@post.save 
+0

哦,我不知道設置'location_id'字段會自動將它們關聯在一起。謝謝。 –

+0

如果您的Post模型與位置(Post有一個位置)有關聯,則最好先查找位置:@ post.location = Location.find(params [:location_id))。 –