views:

34

answers:

2

I'm a newbie to rails, and I have researched a whole day. I think my problem is easy.

There is a table questions_tags_relation, it has two columns(no id):

columns:
question_id -> string
tag_id -> string

And I have a hash:

record = {:question_id=>'111111', :tag_id=>'22222'}

And there is no model 'QuestionsTags', and I don't want to create one.

Now I can get the ActiveRecord::Base.connection, but how to insert the hash to table using simple code? I hope these is a save method:

ActiveRecord::Base.connection.save 'questions_tags', record

Is there such a method?


UPDATE

I'm asking this question because I met some problems when I saved data to the database by using ActiveRecord models. Maybe using connection directly will be simpler. Some of the tables are join tables, they don't have a primary key, that's why there is no id in my example. I hope there is a simple way to save a hash to a table, but I can't find it. Thanks, friends

A: 

If you don't want an ID then your best bet is going to be to address your DB directly. Otherwise just add an id feild and create a Model, its the sensible thing to do unless you have a serious reason not to.

thomasfedb
+1  A: 

On a junction table for a many-to-many relationship, you shouldn't have an id field. In fact, rails will fail loudly if you try to do that since it confuses things.

Typically, if you don't want the join model to be created, just use has_and_belongs_to_many which doesn't require it. Then you can say @question.tags which will do the joining through the appropriate table. You should use the appropriate table name (or override it with :join_table).

Once you've created the association, you can use it like so:

@question.tags << Tag.first
@question.tags.each { |t| t.name }
# ... and so on

Edit: I know this doesn't answer the question of how to connect to the database, but I hope I'm answering the question-behind-the-question of how to access a many-to-many relationship without creating a join model for the intermediary table.

wesgarrison
@wesgarrison: thanks so much, you taught me know the word 'junction table', I was wondering what's the name of these kind of tables in English. And your answer is helpful, thank you:)
Freewind
Great! Does it answer your question or is there something you still need?
wesgarrison
I have read some ActiveRecord source code, and found rails has not 'prepared statement' like Java, I think that's way there is no method to insert a hash to a table, because it's complicated, and not very usefull.
Freewind