在我的数据库中,我试图在出口和文章之间建立一对多的关系。
使用该关系时出现以下错误:
undefined method `outlet_id' for #<Article:0x007fc353887e58>
以下是模型:
class Article < ActiveRecord::Base
belongs_to :analyst
belongs_to :outlet
has_and_belongs_to_many :loe
attr_accessible :article_body, :author, :distribution, :loe, :most_important, :pubdate, :publication, :state, :submitted, :summary, :title, :url, :analyst_id, :loe_ids, :outlet_id
end
class Outlet < ActiveRecord::Base
has_many :articles, foreign_key: :title
attr_accessible :distribution, :name, :state, :article_ids
end
以下是架构:
create_table "articles_loes", :id => false, :force => true do |t|
t.integer "article_id"
t.integer "loe_id"
end
create_table "loes", :force => true do |t|
t.string "name"
t.string "customer"
t.integer "article_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "loes", ["article_id"], :name => "index_loes_on_article_id"
create_table "outlets", :force => true do |t|
t.string "name"
t.integer "articles_id"
t.integer "distribution"
t.string "state"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
add_index "outlets", ["articles_id"], :name => "index_outlets_on_articles_id"
以下是调用:outlet
:
<div class="span4">
<%= f.association :loe %>
<%= f.association :outlet %>
</div>
如果有人有任何想法,我会非常感激他们。我想我可能需要一篇文章中的奥特莱斯索引?如果是这样的话,我真的不确定如何实现。提前谢谢。
答案 0 :(得分:2)
目前,您的Outlet
模型无法与其拥有的articles
相关联。说出belongs_to
后,您需要outlet_id
column
。因此,您需要在outlet_id
模型中添加Article
(整数)列,并使用其所属插座的ID填充它。如果在这种情况下文章可以属于许多网点,则需要通过联合表创建many-to-many
关系。