我正在尝试设置具有Business模型和Category模型的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
商家/ _form.html.erb
...
<div class="field">
<%= f.association :category, input_html: { class: 'chosen-select', multiple: true } %>
</div>
...
商家/ show.html.erb
...
<ul class="tags">
<% @categories.each do |category| %>
<li><%= category.name %></li>
<% end %>
</ul>
...
答案 0 :(得分: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