سؤال

The problem I'm having is that Sinatra apps don't always seem to show my ERB when it is used in some specific context of hyperlinks. I have no idea how much is relevant to show for this question, so I'll do the best I can .Basically, I have a file in my Sinatra app called book_show.erb. It has the following line:

<p><a href="/books/#{@book.id}/edit">Edit Book</a></p>

However, when that link is rendered in the browser, it links like this:

http://localhost:9292/books/#{@book.id}/edit

The #{@book.id} was not replaced with the actual ID value. There is a @book object and I do use it in other contexts in that very same file. For example:

<h1><%= @book.series %></h2>
<h2><%= @book.title %></h2>

<h3>Timeframe:</h3>
<p><%= @book.timeframe %></p>

I don't even know if my routes would make a difference here for diagnosing this but all of the relevant routes for my books functionality are:

get '/books' do
  @title = 'Book Database'
  @books = Book.all
  erb :books
end

get '/books/new' do
  @book = Book.new
  erb :book_add
end

get '/books/:id' do
  @book = Book.get(params[:id])
  erb :book_show
end

post '/books' do
  book = Book.create(params[:book])
  redirect to("/books/#{book.id}")
end

I don't know what else to show to help diagnose this problem. I'm hoping someone sees something terribly obvious that I'm missing.

Adding a book to the database works just fine; it's only that edit link that I can't get to work correctly -- and that would seem to be pure HTML/ERB. In order to test it, I also added this line to the page:

<p>Testing: <%= "/books/#{@book.id}/edit" %>

That came back and returned this text:

Testing: /books/4/edit

So I know the ID is getting stored. It has to be something to do with the hyperlink but I can find nothing useful on Sinatra that helps at all with this.

هل كانت مفيدة؟

المحلول

ERB template does not behave like a ruby string - you need to explicitly tell it you exit the 'template' part into the 'logic' part. It looks very odd when it comes to attributes:

<p><a href="/books/<%= @book.id %>/edit">Edit Book</a></p>

You could use link_to helpers to make it look better:

link_to('Edit Book', controller: 'books', action: 'edit', id: @book.id)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top