简体   繁体   English

如何在轨道上 ruby 的视图中显示关联模型

[英]how to display associated models in views in ruby on rails

This is probably a n00b question.这可能是一个 n00b 问题。 I have CitiesUser model:我有 CitiesUser model:

class CitiesUser < ActiveRecord::Base { belongs_to:city belongs_to:user }

In the controller I do this:在 controller 我这样做:

def index { @cities_users = CitiesUser.find(:all, :conditions => {:user_id => session[:user][:id] }, :include => [:city])

and in the view this:并认为:

<%= @cities_users.inspect %>

Now, I don't see associated model City anywhere.现在,我在任何地方都看不到相关的 model City。 How do I iterate in my view over Cities that are attached to CitiesUser?如何在我的视图中迭代附加到 CitiesUser 的城市?

My WEBRick says:我的 WEBRick 说:

CitiesUser Load (0.6ms) SELECT "cities_users".* FROM "cities_users" WHERE "cities_users"."user_id" = 1

City Load (0.8ms) SELECT "cities".* FROM "cities" WHERE ("cities"."id" IN (5,3))

So the association is being loaded, right?所以正在加载关联,对吧? Which variable is it stored in, or how to I put it inside my CitiesUser?它存储在哪个变量中,或者我如何将它放在我的 CitiesUser 中?

You have to go through the city association.您必须通过城市协会 go。

<%= @cities_users.map{ |cu| cu.city.name }.sort.join(', ') %>

However, if the cities_user table is basically [:user_id, :city_id ], then you have no need for the CitiesUser model at all.但是,如果 city_user 表基本上是 [:user_id, :city_id ],那么您根本不需要 CitiesUser model。 Instead your models should look like:相反,您的模型应如下所示:

class City < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :cities
  ...
end

In your controller, just make sure you have the User record (many auth schemes make this avaiable via a current_user method:在您的 controller 中,只需确保您有用户记录(许多身份验证方案通过current_user方法使其可用:

@user = current_user
@user ||= User.find session[:user][:id]

Then in your view:那么在你看来:

<%= @user.cities.map { |c| c.name }.sort.join(', ') %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM