[英]Access nested model attributes
我有以下设置:
class EmpsController < ApplicationController
def new
@emp = Emp.new
@unit_options = Unit.all.collect{|unit| [unit.name, unit.id] }
end
def create
@emp = Emp.new(emp_params)
@emp.save!
redirect_to :action => :list
end
def destroy
@emp = Emp.find([:id])
@emp.destroy
redirect_to :action => :list
end
def list
@emps = Emp.all
end
def emp_params
params.require(:emp).permit(:name, :unit_id)
end
end
模型:
class Emp < ApplicationRecord
has_one :units
accepts_nested_attributes_for :units
end
形式:
<p> List of Employees: </p>
<table>
<% @emps.each do |u| %>
<tr>
<td><%= u.id %></td> <td><%= u.name %></td> <td><%= u.unit_id %></td> <td><%= link_to "Delete", u, :method => :delete %></td>
</tr>
<% end %>
</table>
我想要做的就是打印(在上表中)名为 :name 与 Emp 打印的 Emp 对象相关的单元属性。
找到了各种相关的解决方案,但它们不适用于我的情况。
首先,不要使用:units
作为关联名称,它“有一个单位”而不是“单位”,Rails 对配置的约定期望关联是单数的。
然后你应该可以做some_emp.unit.name
。
或者您可以使用方法委托:
class Emp < ApplicationRecord
has_one :unit
delegate :name, to: :unit
end
现在你可以做some_emp.name
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.