2015-03-02 73 views
0

我有一個模型位置有很多消息。我試圖讓正在瀏覽位置的用戶向位置所有者發送郵件。Rails中嵌套屬性的自動設置值

我已經location.rb

has_many :messages 
accepts_nested_attributes_for :messages 

和message.rb

belongs_to :location 

在locations_controller.rb

def location_params 
     params.require(:location).permit(:name, 
             :user_id, 
             :image, 
             :latitude, 
             :longitude, 
             location_images_attributes: [:id, :location_id, :location_image, :_destroy], 
             messages_attributes: [:id, :location_id, :from_email, :to_email, :content]) 
    end 

目前,我有我的看法如下代碼:

<%= simple_form_for @location do |l| %> 
    <%= l.simple_fields_for :messages, @location.messages.build do |m| %> 
     <%= m.input :content %> 
     <%= m.input :to_email, :input_html => {:value => @location.user.email}, as: :hidden %> 
    <% end %> 
    <%= l.button :submit %> 
<% end %> 

我不想通過隱藏字段設置電子郵件字段的值,但我想從控制器傳遞值。或者一個模型。請指教。

回答

0

也許嘗試在Location模型這種方法:

class Location < ActiveRecord::Base 
    has_many :messages, after_add: :set_email 
    accepts_nested_attributes_for :messages 

    def set_email(message) 
    message.to_email = user.email 
    end 
end 

基本上你需要註冊一個方法Location,當新信息添加到messages集。

在本例中,我將其命名爲set_email,它將message對象作爲參數,您可以自由修改它。我只是根據locationemail設置to_email

希望這能解決您的問題!

+0

謝謝。經過一番思考,我意識到,該消息有location_id。而位置有user_id,所以我可以通過@ message.location.user.email提取用戶的電子郵件... – luksimir 2015-03-03 11:35:56

0

你可以做這樣的事情在消息模型:

before_create :set_to_email 

def set_to_email 
    self.to_email = self.location.user.email 
end 

缺點是,在每個創建正在執行一些額外的數據庫查詢的操作。所以在規模上這不是性能優化方面的理想解決方案。