是否可以通過兩個has_many
關聯建立一個對象?例如:通過Rails中的兩個關聯構建一個對象
# posts_controller.rb
def create
@post = current_account.posts.build(params[:post])
@post.author = current_user # I want to compact this line into the previous one
end
我做了一些研究,發現這一點:
@article = current_account.posts.build(params[:post], user_id: current_user.id)
但是,沒有工作。在控制檯中,每當我創建一個新對象時,我都會收到user_id: nil
。
我無法實現的另一種可能的解決方案:
@post = current_account.post_with_user(current_user).build(params[:post])
但post_with_user
每個執行我寫失敗。
我協會如下:
class Discussion < ActiveRecord::Base
belongs_to :account
belongs_to :author, class_name: 'User', foreign_key: 'user_id', inverse_of: :discussions
end
class User < ActiveRecord::Base
belongs_to :account
has_many :discussions, inverse_of: :author
end
class Account < ActiveRecord::Base
has_many :users, inverse_of: :account
has_many :discussions
end
我想你可能誤會了我的問題。我添加了我的模型來澄清我的意思。我已經建立了一個作者協會。我的帳戶由子域限定,每個帳戶都有很多用戶。我想確保在創建帖子時,它的作用域是當前帳號,通過子域獲取,並且也與用戶關聯。 – Mohamad
因此,current_account和current_user是不同的對象,並且你確實有一個帖子和作者two_way之間的關係。因此,您可以執行創建後掛鉤建議,或者您可以將作爲author的值傳遞給current_user,並與其他響應者顯示的params合併,但使用不同的散列鍵值:@article = current_account.posts.build( params [:post] .merge({:author => current_user}))。這裏最重要的是構建調用需要一個散列,其中散列的鍵是關聯名稱或正在構建的對象的字段名稱。 – LisaD