I have two tables: interests and Link_ui (this is for recording user and interest)
I want to input the user id and show all interests name that user have.
In Link_ui controller:
def output
@interests = LinkUi.find_by_sql [ 'SELECT interests.name FROM link_uis, interests
WHERE link_uis.interest_id = interests.id AND link_uis.user_id=? ', params['user_id'] ]
And input page:
<%= form_tag :action => 'output', :method => 'post' %>
enter id.
<%= text_field_tag ':user_id', '', 'size' => 30 %>
It comes out nothing, but I am sure there is matched data in database. And if I don’t input parameter just set link_uis.user_id = 1, it comes out:
your search are [#<LinkUi >, #<LinkUi >, #<LinkUi >, #<LinkUi >]
What’s wrong with this..
Well,
find_by_sqlon a LinkUi model expects you to return columns from thelink_uistable, whereas you’re selecting justinterests.name. However, you are picking a bit of a fight with ActiveRecord, there. 🙂You usually want to avoid
find_by_sql, and instead let ActiveRecord generate your SQL for you. Probably most important for your example are associations.The way I see it, you have a bunch of Users, and a bunch of Interests. Your LinkUis tie these two together (a LinkUi belongs to a User and an Interest). Feel free to correct me on this; this is your business logic as I gather from your example.
These classes (whose names I’ve emphasized) are your models, defined in the
app/modelsdirectory. The assocations (relationships) between them should be defined on those classes.Start of with a simple association in your User model:
And in your Interest model:
Then the LinkUi model that ties it together:
Now, given any User, you can get his/her LinkUis by simply saying
user.link_uis.all, and for each LinkUi, you can get the Interest aslink_ui.interest. You can tell ActiveRecord to try and fetch these two in one shot as efficiently as possible using:include, and get a list of Interest names using the standard Rubycollectmethod. It then becomes:You can take it one step further; for any User, you can directly get his/her Interests. Once you’ve set up the above associations, you can fold two ‘steps’ into one, like this:
Which could turn the example into this one-liner: