Проблема после проблемы ха-ха, но я так близок к завершению моего проекта !!
Поэтому у меня есть программа Ruby on Rails, выполненная и работающая. Теперь я пытаюсь интегрировать его в HTML-шаблон.
Наконец, я получил графику и шаблон для правильной загрузки, но только для страницы index.html.erb с этой начальной страницы. Теперь моя проблема - это страница, определенная как " результат " из моего файла контроллера, не будет отображаться правильно. Похоже, это может быть легко исправить, но не знаю, как это сделать. Похоже, что встроенные стили css работают правильно на основе формата результата, но изображения и стили в моем стиле.css теперь не загружаются для шаблона (кроме индекса).
Я помещал каталог изображений в качестве подкаталога public. У меня также есть style.css.
У меня есть страница в представлениях, называемых " customerdisplay.html.erb ", которая содержит HTML-код для моего шаблона. Один из тегов div в этом файле - это пользовательский div в моей внешней таблице стилей, но когда я использую этот тег, я также устанавливаю выравнивание в центр. Центрирование работает, но все остальное из внешней таблицы стилей не работает.
Я добавлю код контроллера и код представления для справки.
Как я могу заставить внешнюю таблицу стилей и изображения работать для "def result" в моем файле контроллера?
class MyRubyController < ApplicationController
def index
# the first user screen is displayed:
# index.html.erb in views/myRuby directory
# This controller is executed
end
def result
# when the user presses submit, result is called
@data = params[:data] # The data text field
@field = params[:field] # the request
# check for nondigits in the data
if @data =~ /\D/
# if a nondigit, invalid.html.erb is displayed
render :action => 'invalid'
else # valid data
case @field # check the request
when "cu" then # customer data request
# Verify that customer is in the customer table
if Customer.exists?(@data)
# exists, display custdisply.html.erb
render :action => 'custdisplay'
else
# does not, display notfound.html.erb
render :action => 'notfound'
end
when "sr" then # sales rep request
if Customer.exists?(@data)
# exists, display salesrepdisplay.html.erb
render :action => 'salesrepdisplay'
else
# does not, display notfound.html.erb
render :action => 'notfound'
end
when "or" then #orders request
if Customer.exists?(@data)
# exists, display orderdisplay.html.erb
render :action => 'orderdisplay'
else
# does not, display notfound.html.erb
render :action => 'notfound'
end
when "p" then #parts request
if Customer.exists?(@data)
# exists, display partsdisplay.html.erb
render :action => 'partsdisplay'
else
# does not, display notfound.html.erb
render :action => 'notfound'
end
end # end case
end # end if valid data
end
def custdisplay
end
def salesrepdisplay
end
def orderdisplay
end
def partsdisplay
end
def notfound
end
def invalid
end
end
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head profile="http://gmpg.org/xfn/11">
<link rel="stylesheet" type="text/css" href="style.css">
<title>The Justin Geis Data Access Program</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div id="logo"><img src="images/logo.png"></div>
<div id="container">
<div id="header">
<!--blank.. could add stuff if wanted.. -->
</div>
<div id="content" align="center">
<h1>Spartan Hardware Data Access</h1>
<% # get the customer data from the customer table
@custdata = Customer.find(@data)
# copy each field into a variable for display
@id = @custdata.id
@ln = @custdata.last_name
@fn = @custdata.first_name
@bl = @custdata.balance;
@bl = sprintf("%7.2f",@bl) # format as currency
@cl = @custdata.credit_limit
@cl = sprintf("%7.2f",@cl) # format as currency
@sr = @custdata.sales_rep
%>
<h1>customer data for customer: <%=@data %></h1>
<table border=1>
<tr>
<td>ID</td>
<td>Last name</td>
<td>First name</td>
<td>Balance</td>
<td>Credit limit</td>
<td>Sales rep</td>
</tr>
<tr>
<td><%=@id%></td>
<td><%=@ln%></td>
<td><%=@fn%></td>
<td><%=@bl%></td>
<td><%=@cl%></td>
<td><%=@sr%></td>
</tr>
</table>
</div>
<div id="footer"><!--nothing right now --></div>
</div>
</body>
</html>
Ваше представление визуализируется внутри другого представления, называемого макетом, обычно в файле app/views/layouts/application.html.erb
. Вот почему ваш <head>
не будет работать, потому что он внутри <body>
.
2 варианта:
yield
в макете, которая дает тег из content_for
внутри вашего представления salesrepdisplay
. http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_forrender :action => 'salesrepdisplay'
, используйте render :action => 'salesrepdisplay', :layout => nil
href="style.css"
, поэтому она зависит от того, где находится ваша страница, является ли ваш style.css
public/
или сгенерирован из app/assets
. Я настоятельно рекомендую сделать это способом Rails, сначала прочитав официальное руководство по компоновке и просмотрам guides.rubyonrails.org/layouts_and_rendering.html