gpt4 book ai didi

ruby-on-rails - Rails4 : How to display the data when association data doesn't exist

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:50 24 4
gpt4 key购买 nike

我想做的是将数据显示如下;

  • 如果 a.title 存在但 @school.rooms.where(day: d).first.name 不存在,则显示 a.title '存在
  • 如果 a.title 不存在但 @school.rooms,则显示 @school.rooms.where(day: d).first.name。 where(day: d).first.name 存在

如果两个数据都存在,它就有效。尽管我尝试了一些代码,例如exist?nil? 等等,但我不能。

如果你能给我最好的 Rails 方法,我将不胜感激。

查看代码

<div class="row">
<h1 class="col-md-12"><%= @school.title %></h1>
</div>
<div class="row">

<% @school.days.each do |d| %>

<h3>Day<%= d %></h3>

<% @school.articles.where(day: d).each do |a| %>
<strong><%= a.title %></strong></p>
<% end %>

<p>Room: <%= @school.rooms.where(day: d).first.name %></p>

<% end %>

</div>

Controller 代码

class SchoolsController < ApplicationController
def show
@school = School.find(params[:id])
end
end

模型代码

class School < ActiveRecord::Base
has_many :articles
has_many :rooms

def days
self.articles.pluck(:day).uniq
end
end


class Article < ActiveRecord::Base
belongs_to :school
end


class Room < ActiveRecord::Base
belongs_to :school
end

架构

ActiveRecord::Schema.define(version: 20150999999999) do

create_table "rooms", force: true do |t|
t.integer "school_id"
t.integer "day"
t.string "name"
t.string "detail"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "articles", force: true do |t|
t.integer "school_id"
t.integer "day"
t.string "start_time"
t.string "end_time"
t.integer "category"
t.string "title"
t.string "contents"
t.datetime "created_at"
t.datetime "updated_at"
end

create_table "schools", force: true do |t|
t.string "title"
t.datetime "created_at"
t.datetime "updated_at"
end

如果您能给我任何建议,我们将不胜感激。

最佳答案

如果你总是有任一个数据存在(IE a.title存在如果@school.rooms.where(day: d).first .name 没有),您可以使用以下内容:

<p>Room: <%= a.title || @school.rooms.where(day: d).first.name %></p>

如果两者均不存在,您应该能够使用“默认”值:

<p>Room: <%= a.title || @school.rooms.where(day: d).first.name || "default" %></p>

关于ruby-on-rails - Rails4 : How to display the data when association data doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com