简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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