Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RubyonRails从中获取name和show有很多方法_Ruby On Rails_Ruby_Ruby On Rails 4 - Fatal编程技术网

Ruby on rails RubyonRails从中获取name和show有很多方法

Ruby on rails RubyonRails从中获取name和show有很多方法,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我们有一个用户表,也有一个国家表,其关联如下所示 user.rb has_many :user_countries has_many :countries, :through => :user_countries user_country.rb belongs_to :user belongs_to :country country.rb has_many :users, :through => :user_countries 现在我想要的是获取国家名称并将其显示在sq

我们有一个用户表,也有一个国家表,其关联如下所示

user.rb

has_many :user_countries
has_many :countries, :through => :user_countries


user_country.rb

belongs_to :user
belongs_to :country

country.rb

has_many :users, :through => :user_countries
现在我想要的是获取国家名称并将其显示在sql记录中,这样新的user\u country列就会出现,它将在获取用户时显示用户的国家

data = User.select("users.*, countries.name as country_name").
            joins("INNER JOIN `user_countries` ON `user_countries`.`user_id ` = `users`.`id`").
            joins("INNER JOIN `countries` ON `countries`.`id ` = `user_countries`.`country_id`")

到目前为止,我一直在尝试这样做,但没有成功,因为它抛出了mysql错误。我需要一个额外的列,提供国家名称作为额外的列。请帮我解决这个问题。

看起来你在试图建立一种多对多的关系。这可以非常简单地通过
has\u和\u属于\u many
关联来实现。请看。

因为您已经在使用activerecord关联,所以可以按如下方式使用active record查询:

User.joins(:countries).select("users.*, countries.name as country_name")

您可以了解有关select的更多信息

这一行不清楚/混乱
将其显示在sql记录中,这样新的user\U country列就会出现,它将在获取用户时显示用户的国家
预期的输出是什么?我的意思是,如果我在例如mysql中运行原始sql查询,那么应该会有额外的输出用户记录中名为country\u name的列,在获取用户时将附加到该列的末尾。您是否收到任何错误?'on'子句中的未知列user\u countries.user\u id:
user.joins(:countries)。选择(“users.*,countries.name as country\u name”)