【问题标题】:Association Companies industries in rails铁路行业协会公司
【发布时间】:2014-02-23 01:06:49
【问题描述】:

我在公司和行业之间创建了多对多关系,因此当我创建公司时,我可以从公司的一个或多个行业的精选集合中进行选择。一旦公司创建并重定向到公司页面,我就无法获得公司的行业信息。有人可以帮我理解为什么吗?

这是我的公司模式

class Company < ActiveRecord::Base
    has_many :industres
    has_many :industies, through: :industrializations
end

这是我的行业模式

class Industry < ActiveRecord::Base
    has_many :industrializations
    has_many :companies, through: :industrializations
end

这是我的工业化模式

class Industrialization < ActiveRecord::Base
    belongs_to :company
    belongs_to :industry
end

这是我的 _form.html.erb

<%= f.label :industry %><br />
<%= f.collection_select :industry_ids, Industry.all, :id, :name, :prompt => "Choisir votre secteur d'activité"  %>

这是我的公司 show.html.erb

<p>
  <strong>Name:</strong>
  <%= @company.name %>
</p>

<p>
  <strong>Description:</strong>
  <%= @company.description %>
</p>

<p>
  <strong>Country:</strong>
  <%= @company.country %>
</p>

<p>
  <strong>City:</strong>
  <%= @company.city %>
</p>

<b>Sector:</b>
<ul>
  <% @company.industries.each do |industry| %>
    <li><%= industry.name %></li>
  <% end %>
</ul>

这是我的架构

create_table "companies", force: true do |t|
    t.string   "name"
    t.text     "description"
    t.string   "country"
    t.string   "city"
    t.datetime "created_at"
    t.datetime "updated_at"
end

create_table "industrializations", force: true do |t|
    t.integer  "company_id"
    t.integer  "industry_id"
    t.datetime "created_at"
    t.datetime "updated_at"
end

create_table "industrie", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
end

行业名称在种子文件中

公司模型是通过脚手架创建的

【问题讨论】:

  • 你能分享这三个的架构吗?
  • 控制器代码以及您拥有的任何日志信息也会有所帮助。
  • 我猜你的Company 模型中有错字。应该是has_many :industries, through: :industrializations

标签: ruby-on-rails ruby ruby-on-rails-4 associations


【解决方案1】:

您已将其标记为 Rails 3.2 和 Rails 4,但它们各自有不同的方式通过控制器将表单信息接收到模型。

在 Rails 3.2 中,您必须确保将 industry_ids 属性标记为 attr_accessible。但由于您没有抱怨“质量分配”错误,我认为您可能在 Rails 4 上。

在 Rails 4 中,您现在需要使用“强参数”来允许参数通过模型 - 您可能会发现脚手架控制器已经为公司的其他属性执行此操作,您只需添加行业 ID 以允许他们。

有关更多信息,请参阅How is attr_accessible used in Rails 4?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多