I have following tables:
create table files ( id int auto_increment primary_key name varchar(255) )
create table users ( id int auto_increment primary_key name varchar(255) )
create table admins ( file_id int user_id int )
I would like to be able to say get the user names of the file admin. How do I create an association to 开发者_高级运维get this one
If I do has_many :admins on the files, then I can do file.admins to get the ids and to get the user names of those admins I would have to sub queries using the Find. I would like to avoid that one
For Rails questions, rather than sharing your database create-table syntax, you should share your database migrations (just open up schema.rb and copy/paste).
It looks like you just have users, some of whom have admin privileges. The easier way of doing this is to just have a t.boolean :admin, :default => false
column on your user model.
A nice benefit of this approach is that Active Record will provide you with a User#admin?
method that is highly readable in conditionals and such (i.e. <%= render 'admin_menu' if @user.admin? %>
).
This also sidesteps your concerns about additional queries to get the usernames after getting the listed admins.
# app/models/file.rb
class File < ActiveRecord::Base
belongs_to :user
end
@files = File.where(:something => true).include(:user)
@files.map(&:name) #=> ['Bob', 'Cindy', ...]
精彩评论