Rails 3有新的方法来获取主键吗?

时间:2021-02-06 18:49:57

I am trying to go through a learning rails book, but I keep running into road bumps as it is meant for rails 2.something. I have been able to get around them until now, while the script still runs almost perfectly fine, it lacks one function... I have the following code in ads_controller.rb:

我正在尝试通过学习轨道书,但我继续遇到道路颠簸,因为它是用于rails 2.something。到目前为止,我已经能够绕过它们,而脚本仍然运行得非常完美,它缺少一个功能......我在ads_controller.rb中有以下代码:

 class AdsController < ApplicationController
  def create
    @ad = Ad.new(params[:ad])
    @ad.save
  end
    def new
    @ad = Ad.new
  end


  def show
    @ad = Ad.find(params[:id])
  end


  def index
    @ads = Ad.find(:all)
  end

end

Thefollowing Code In routes.rb:

以下代码在routes.rb中:

    MeBay::Application.routes.draw do |map|

  map.connect '/ads/new', :controller=>'ads', :action=>'new'
  map.connect '/ads/create', :controller=>'ads', :action=>'create'
  map.connect '/ads/', :controller=>'ads', :action=>'index'
  map.connect '/ads/:id', :controller=>'ads', :action=>'show'
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action;:id.:format' 

The following in new.html.erb:

new.html.erb中的以下内容:

<h1>New Ad</h1>
<%= form_for @ad, :url=>{:action=>'create'} do |f| %>
    <p><b>Name:</b><br /><%= f.text_field:name %></p>
    <p><b>Description</b><br /><%= f.text_area:description %></p>
    <p><b>Price</b><br /><%= f.text_field:price%></p>
    <p><b>Seller</b><br /><%= f.text_field:seller_id%></p>
    <p><b>Email</b><br /><%= f.text_field:email %></p>
    <p><b>Image URL</b><br /><%= f.text_field:img_url %></p>
    <p> <%= f.submit "Create" %> </p>
<% end %>

and the Following in create.html.erb:

和create.html.erb中的以下内容:

<h3>NEW AD CREATED FOR <%= @ad.name %>!</h3>
<a href="/ads/<% @ad.id %>">Click To View</a>

What happens, when I click on the submit button when on the new page I get transfered to the create template, which displays the name, however, it can not get the id from the variable and thus returns to the list page, but it is suppose to return to the ads newly created page..(ie.. /ads/7, but returns /ads/)

会发生什么,当我在新页面上点击提交按钮时,我会转移到创建模板,该模板显示名称,但是,它无法从变量中获取id,因此返回到列表页面,但它是假设要返回新创建的广告页面..(即.. / ads / 7,但返回/广告/)

Is there a syntax problem or a new way to get it in rails 3?

是否存在语法问题或在rails 3中获取它的新方法?

1 个解决方案

#1


3  

Change:

<a href="/ads/<% @ad.id %>">Click To View</a>

With:

<a href="/ads/<%= @ad.id %>">Click To View</a>

By the way, why don't you use url helpers?

顺便问一下,你为什么不使用网址助手?

#1


3  

Change:

<a href="/ads/<% @ad.id %>">Click To View</a>

With:

<a href="/ads/<%= @ad.id %>">Click To View</a>

By the way, why don't you use url helpers?

顺便问一下,你为什么不使用网址助手?