如何加入这个表?
我是 Rails 新手
错误
Mysql2::Error: Unknown column 'states.ad_id' in 'where clause': SELECT `states`.* FROM `states` WHERE (`states`.ad_id = 1) LIMIT 1
我的模型
ad.rb
has_one :state
state.rb
belongs_to :ad
这是我的表格。
广告表格
+----+----------------+-------------+-------+-----------+
| id | title | description | price | states_id |
+----+----------------+-------------+-------+-----------+
| 1 | ebook | asdasd | 1 | 1 |
| 2 | iphone 4 devol | sdfsdf | 1 | 1 |
| 3 | asd | asd | 1 | 2 |
+----+----------------+-------------+-------+-----------+
状态表
+----+----------+
| id | name |
+----+----------+
| 1 | Pluto |
| 2 | Mars |
+----+----------+
im new to rails
error
Mysql2::Error: Unknown column 'states.ad_id' in 'where clause': SELECT `states`.* FROM `states` WHERE (`states`.ad_id = 1) LIMIT 1
my model
ad.rb
has_one :state
state.rb
belongs_to :ad
here are my tables.
ads table
+----+----------------+-------------+-------+-----------+
| id | title | description | price | states_id |
+----+----------------+-------------+-------+-----------+
| 1 | ebook | asdasd | 1 | 1 |
| 2 | iphone 4 devol | sdfsdf | 1 | 1 |
| 3 | asd | asd | 1 | 2 |
+----+----------------+-------------+-------+-----------+
states table
+----+----------+
| id | name |
+----+----------+
| 1 | Pluto |
| 2 | Mars |
+----+----------+
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的错误消息告诉您 states 表中没有 ad_id 列。
您可能想使用 states.id 而不是 states.ad_id
Your error message tells you that you dont have ad_id column in the states table.
You probably wanted to use states.id instead of states.ad_id
请参阅它是属于还是属于关联? http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods 部分.html
在您的示例中,您可能希望
状态
has_many :ads
广告
belongs_to :state
如下指定多对一关系而不是一对一关系,因为一个州可以有许多广告
see the Is it a belongs_to or has_one association? section of http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
in your example you probably want
state
has_many :ads
ad
belongs_to :state
as you are specifying a many to one as opposed to a one to one relationship, since a state can have many ads