我正在尝试设置一个rails应用程序,该应用程序具有业务模型和类别模型。一个业务可以有多个类别,并且这些类别可以属于多个业务。
一切似乎都正常工作,我没有收到任何错误,除了试图显示与特定业务相关的类别时,没有显示任何内容。
以下是我的模型、控制器和视图。这是我的第一个rails项目,我正在寻求一些帮助。
business.rb
class Business < ActiveRecord::Base
attr_accessible :category_id
belongs_to :category
end
类别.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>
...
考虑到您希望一个企业有许多类别,您的模型的关系应该更新如下:
业务
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
然后,在您的控制器中,您可以访问数据:
业务控制器
def show
@business = Business.find(params[:id])
@categories = @business.categories
respond_to ...
end