ruby-on-rails - 列出 Rails 中属于另一个模型的所有模型

标签 ruby-on-rails associations has-many has-one

在“服务”模型的显示 View 中,我希望能够显示与此服务关联的所有“评论”。需要知道在“服务”显示 View 以及“服务”/“评论” Controller 中放置什么。

服务模式:

class Service < ActiveRecord::Base
  has_many :reviews
end

审查模型:

class Review < ActiveRecord::Base
  has_one :service
  belongs_to :service
end

服务展示 View :

<table>
<thead>
    <tr>
      <th>Name</th>
      <th>Date</th>
      <th>Review</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @reviews.each do |review| %>
      <tr>
        <td><%= review.name %></td>
        <td><%= review.date %></td>
        <td><%= review.review %></td>
        <td><%= link_to 'Show', review %></td>
        <td><%= link_to 'Edit', edit_review_path(review) %></td>
        <td><%= link_to 'Destroy', review, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

查看架构:

  create_table "reviews", force: true do |t|
    t.string   "name"
    t.string   "date"
    t.text     "review"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "service_id"
  end

审查 Controller :

def index
    @reviews = Review.all
    respond_with(@reviews)
  end

  def show
    respond_with(@review)
  end

  def new
    @review = Review.new
    respond_with(@review)
  end

  def edit
  end

  def create
    @review = Review.new(review_params)
    @review.save
    respond_with(@review)
  end

服务 Controller :

  def new
   @service = Service.new
  end

  # GET /services/1/edit
  def edit
  end

  # POST /services
  # POST /services.json
  def create
    @service = Service.new(service_params)

    respond_to do |format|
      if @service.save
        format.html { redirect_to @service, notice: 'Service was successfully created.' }
        format.json { render :show, status: :created, location: @service }
      else
        format.html { render :new }
        format.json { render json: @service.errors, status: :unprocessable_entity }
      end
    end
  end

最佳答案

如果您想在服务显示页面中显示与该服务相关的所有评论,则需要调整您的service_controller 显示 像这样的 Action

def show
  @service = Service.find(params[:id])
  @reviews = @service.reviews
end 

关于ruby-on-rails - 列出 Rails 中属于另一个模型的所有模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30955440/

相关文章:

ruby-on-rails - 模型 -> has_many -> 两次

ruby-on-rails - 抓取 instagram 关注者的单元测试

grails - 在grails条件中转义关联名称不与包含类变量名称冲突

go - 双向预加载“属于”关联

ruby-on-rails - Rails 3 has_many 改变了吗?

ruby-on-rails - Rails3 : how to set default conditions to has_many

ruby-on-rails - 登录后重定向到原始目的地

ruby-on-rails - 在 Windows 上运行的 Ubuntu bash 上设置 PostgreSQL

ruby-on-rails - 简单的 RoR 下拉框,将值作为参数传递

ruby-on-rails - 有_许多 :through without a join table