简体   繁体   English

我找不到直接在Rails中将值保存在哈希中的方法

[英]I can't find a method to save the values in a hash directly in rails

I'm a newbie to rails, and I have researched a whole day. 我是Rails的新手,并且研究了一整天。 I think my problem is easy. 我认为我的问题很容易。

There is a table questions_tags_relation , it has two columns(no id): 有一个表questions_tags_relation ,它有两列(无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. 而且没有模型'QuestionsTags' ,我也不想创建一个模型。

Now I can get the ActiveRecord::Base.connection , but how to insert the hash to table using simple code? 现在,我可以获取ActiveRecord::Base.connection ,但是如何使用简单的代码将哈希插入表呢? I hope these is a save method: 我希望这些是save方法:

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. 我之所以问这个问题,是因为使用ActiveRecord模型将数据保存到数据库时遇到了一些问题。 Maybe using connection directly will be simpler. 也许直接使用connection会更简单。 Some of the tables are join tables, they don't have a primary key, that's why there is no id in my example. 一些表是join表,它们没有主键,这就是为什么我的示例中没有id的原因。 I hope there is a simple way to save a hash to a table, but I can't find it. 我希望有一种简单的方法可以将哈希保存到表中,但我找不到它。 Thanks, friends 谢谢朋友

On a junction table for a many-to-many relationship, you shouldn't have an id field. 在用于多对多关系的联结表上,您不应具有id字段。 In fact, rails will fail loudly if you try to do that since it confuses things. 实际上,如果您尝试这样做,rails将大声失败,因为它会使事情变得混乱。

Typically, if you don't want the join model to be created, just use has_and_belongs_to_many which doesn't require it. 通常,如果您不希望创建连接模型,只需使用has_and_belongs_to_many即可 ,该方法不需要它。 Then you can say @question.tags which will do the joining through the appropriate table. 然后,您可以说@question.tags ,它将通过相应的表进行联接。 You should use the appropriate table name (or override it with :join_table). 您应该使用适当的表名(或用: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. 编辑:我知道这不会回答如何连接到数据库的问题,但我希望我回答了如何在不创建联接模型的情况下访问多对多关系的问题用于中间表。

If you don't want an ID then your best bet is going to be to address your DB directly. 如果您不需要ID,那么最好的选择就是直接寻址数据库。 Otherwise just add an id feild and create a Model, its the sensible thing to do unless you have a serious reason not to. 否则,只需添加一个id费尔德和创建一个模型,其明智的做法,除非你有一个很重要的理由不这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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