开发者

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..

 SELECT users.name, events.* FROM users, events WHERE users.id=events.uid

Thanks a lot.

I rename 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 both开发者_运维问答ering you guys..


Assuming you have set up your associations you should be able to do it like so:

u = Users.find(:all, :include => :events, :conditions => "users.id == events.uid")


You can use the find_by_sql function to execute arbitrary SQL, so in your case you could do:

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, e.g. puts e.user_name. Of course it is not possible to change the username since it was generated in a SQL query.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜