【问题标题】:Adding Multiple Categories to a Business Model in Rails在 Rails 中为业务模型添加多个类别
【发布时间】:2014-09-24 23:03:57
【问题描述】:

我正在尝试设置一个具有业务模型和类别模型的 Rails 应用程序。一个企业可以有多个类别,并且这些类别可以属于多个企业。

一切似乎工作正常,我没有收到任何错误,除非尝试显示与特定业务相关的类别时没有显示任何内容。

以下是我的模型、控制器和视图。这是我的第一个 Rails 项目之一,正在寻求帮助。

business.rb

class Business < ActiveRecord::Base

  attr_accessible :category_id
  belongs_to :category

end

category.rb

class Category < ActiveRecord::Base

  attr_accessible :name, :description
  has_many :businesses

end

business_controller.rb

def show
  @business = Business.find(params[:id])
  @categories = Category.where(:business_id => @business).all

  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @business }
  end
end

def new
  @business = Business.new
  @categories = Category.order(:name)

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @business }
  end
end

def edit
  @business = Business.find(params[:id])
  @categories = Category.order(:name)
end

business/_form.html.erb

...

<div class="field">
    <%= f.association :category, input_html: { class: 'chosen-select', multiple: true } %>
</div>

...

business/show.html.erb

...

<ul class="tags">
  <% @categories.each do |category| %>
    <li><%= category.name %></li>
  <% end %>
</ul>

...

【问题讨论】:

  • 您写的关于模型的内容与您使用代码显示的内容之间似乎存在冲突。您注意到一个企业可以有许多类别,并且一个类别属于一个企业。但是,您的模型与您编写的相反(一个业务属于一个类别,该类别有许多业务)。将有助于澄清哪种架构是正确的。
  • @craig.kaminsky 我想为一个企业分配多个类别。

标签: ruby-on-rails-3 associations categories


【解决方案1】:

鉴于您希望企业拥有多个类别,您的模型的关系应更新如下:

商业

def Business < ActiveRecord::Base
  has_many :categories
  attr_accessible :name, :etc
  # attr_accessible :category_id would not apply as the business model 
  # would not have this relationship
end

类别

def Category < ActiveRecord::Base
  attr_accessible :business_id, :name, :description
  belongs_to :business
end

然后,在您的控制器中,您可以访问数据:

BusinessesController

def show
  @business = Business.find(params[:id])
  @categories = @business.categories 
  respond_to ... 
end

【讨论】:

  • 现在我遇到的唯一问题是我无法批量分配受保护的属性(参见图片:cl.ly/image/3x0W0208023E/o)。我正在尝试从业务/编辑视图为每个业务设置类别。
  • 您应该能够将:category_id 添加到业务模型中的attr_accessible 表达式中。这假设您使用的是 Rails 3.x(看起来您是)。
  • 成功了!非常感谢克雷格的耐心和支持!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多