Ruby on rails 自动设置Rails中嵌套属性的值
我有一个模型位置,其中有许多信息。我试图让浏览位置的用户向位置所有者发送消息 我有location.rbRuby on rails 自动设置Rails中嵌套属性的值,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我有一个模型位置,其中有许多信息。我试图让浏览位置的用户向位置所有者发送消息 我有location.rb has_many :messages accepts_nested_attributes_for :messages 和message.rb belongs_to :location 在位置_controller.rb中 def location_params params.require(:location).permit(:name,
has_many :messages
accepts_nested_attributes_for :messages
和message.rb
belongs_to :location
在位置_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 %>
{:value=>@location.user.email},as::hidden%>
我不想通过隐藏字段设置电子邮件字段的值,但我想从控制器传递值。或者一个模型。请告知。您可以在消息模型中执行以下操作:
before_create :set_to_email
def set_to_email
self.to_email = self.location.user.email
end
缺点是每次创建操作都会执行一些额外的数据库查找。因此,就性能优化而言,这并不是一个理想的解决方案 也许可以在您的
位置
模型中尝试这种方法:
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
类位置
基本上,当新消息添加到消息
集中时,您必须为位置
注册一个方法
在本例中,我将其命名为set\u email
,它以message
对象作为参数,您可以自由修改它。我只是根据位置的电子邮件设置
希望这能解决你的问题 谢谢。经过一番思考,我意识到,这封邮件有location_id。location有user_id,所以我可以通过@message.location.user.email提取用户的电子邮件。。。