[英]ROR: MySQL query expression
I have set up the Model, but I don't know how to write the code in controller to get result of the following SQL query.. 我已经设置了模型,但是我不知道如何在控制器中编写代码以获取以下SQL查询的结果。
SELECT users.name, events.* FROM users, events WHERE users.id=events.uid
Thanks a lot. 非常感谢。
I rename events.uid -> events.user_id 我重命名events.uid-> events.user_id
And set up the Model for both of them, attributes of events are 并为它们两个都设置模型,事件的属性是
t.integer :user_id
t.string :title
t.datetime :hold_time
t.string :place
t.text :description
And new error is 而新的错误是
undefined method title for #<User:0x3fb04d8>
Sorry for bothering you guys.. 抱歉打扰你们..
假设您已经建立了关联,那么您应该可以这样做:
u = Users.find(:all, :include => :events, :conditions => "users.id == events.uid")
I cant comment yet (not enough rep), so I am posting an answer, but the: 我还不能发表评论(代表人数不足),所以我发布了答案,但是:
"users.id == events.uid"
should be: 应该:
"users.id = events.uid"
I am not sure that will solve your problem, but it may. 我不确定是否可以解决您的问题,但是可以。
if you want to find all users and events, you can do it like this: 如果要查找所有用户和事件,可以这样进行:
users = User.all
users.each do |user|
= user.name
user.events.each do |event|
= event.name
end
end
and your models would look like this: 您的模型将如下所示:
class User < ActiveRecord::Base
has_many :events
end
class Event < ActiveRecord::Base
belongs_to :user
end
I am sure there is another way to do it with event.uid, but I am not that advanced yet. 我敢肯定,还有另一种使用event.uid的方法,但是我还没有那么先进。
You can use the find_by_sql
function to execute arbitrary SQL, so in your case you could do: 您可以使用
find_by_sql
函数执行任意SQL,因此您可以执行以下操作:
e = Event.find_by_sql( 'SELECT events.*, users.name as user_name from users, events where user.id = events.uid')
e
would now contain all events with matching user names and you can access the user name just like any other attribute, eg puts e.user_name
. 现在
e
将包含具有匹配用户名的所有事件,并且您可以像访问其他任何属性一样访问该用户名,例如puts e.user_name
。 Of course it is not possible to change the username since it was generated in a SQL query. 当然,由于用户名是在SQL查询中生成的,因此无法更改用户名。
This approach may not be in accordance with Rails philosophy of DB agnostic applications, however I find that it is sometimes much easier (and probably faster) to use SQL directly instead of trying to achieve the same thing with ActiveRecord. 这种方法可能与数据库无关应用程序的Rails原理不一致,但是我发现有时直接使用SQL而不是尝试通过ActiveRecord实现同一目的要容易得多(可能更快)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.