-2

我有title, text, and user_id在rails中如何「自動」保存一個user_id用於說一篇文章(其中有一個user_id列)由經過身份驗證的用戶發佈? [:PARAMS]

在該文章控制器創建行動的文章表,使用保存文章之前從瀏覽器中,我加入這一行:

article.user_id = session[:user_id] 
article.save 

現在,因爲我想這是業務邏輯,我認爲它應該發生在文章模型中,這將確保數據由發佈它的作者保存,但我不知道如何在模型中使用會話。

任何人都可以幫忙嗎?或者,也許建議最好的做法來處理這種情況?

感謝

+0

@tereško這個問題是如何尋求幫助和最佳實踐的請求在真實案例中處理MVC架構設計,以達到良好的軟件設計目的,但同時(也是最重要的)爲了避免潛在的安全風險,爲什麼要關閉它? 跑出高清空間? :D –

回答

1

這樣做是如下

@user = User.find(session[:user_id]) 
article = @user.articles.build(params[:article]) 
article.save 

假設params[:article] = {:title => "Test Title", :description => "Test Description"}

然後

article = @user.articles.build(params[:article]) 

正確方法是一樣的

article = Article.new(:title=>params[:article][:title], 
         :description =>params[:article][:description], 
         :user_id => @user.id) 

這意味着These objects will be instantiated from the passed attributes, and the link through their foreign key (i.e. 'user_id' in your case) will be created, but the associated objects will not yet be saved.

參考this更多細節

注: - 我假設用戶有很多文章

+0

是用戶has_many的文章,但是你能更好地解釋第二行的內容嗎?謝謝 –

+0

檢查我編輯的答案,並請在任何查詢的情況下免費。 – Salil

+0

感謝您的解釋,但仍然不應該在模型內而是在控制器內發生這一切?如果它一定是這樣的話,那麼你能否指出我編碼它的方式的弱點? –

相關問題