2013-03-11 119 views
0

有没有办法让外国模型的某些领域是这样的:Rails的:获取与方法子模型的某些属性的“属性”

@user = User.find(:first, :select => ['`users`.`id`, `users`.`nickname`, `users`.`birthdate`, `users`.`sex`'], :conditions => ['`users`.`id` = ?', id]) 

city = @user.profile.city.attributes 

随着attributes我找回我的城市模型的所有属性。我只想得到一些。例如:

city = @user.profile.city.attributes[:name, :postcode] 

是否可以通过保持语法如上所述简单?我想用attributes来接收哈希。

非常感谢。

回答

0

按照您的方式链接时,无法选择外国模型的字段。唯一的办法是在城市模型上进行查询:

City.where(:profile_id => @user.profile.id, :select => ...) 
+0

好:(谢谢! – Gozup 2013-03-11 11:12:50

0

您不能在属性之后提供参数,否则会引发ArguementError。在这种情况下,您可以使用内部联接来获取记录。

1

你可以这样做,如果你不介意它挑出领域SQL返回后一切:

@user.profile.city.attributes.select{|k,v| ["name","postcode"].include?(k)} 
0
city = @user.profile.city.pluck(:name, :postcode)