Rails表单对象显示操作

时间:2013-08-01 06:49:45

标签: ruby-on-rails forms

我想弄清楚如何编写表单对象的show动作。

以下是从RailsCast第416集project

中获取的代码

应用/形式/ signup_form.rb

class SignupForm
  # Rails 4: include ActiveModel::Model
  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  def persisted?
    false
  end

  def self.model_name
    ActiveModel::Name.new(self, nil, "User")
  end

  validates_presence_of :username
  validate :verify_unique_username
  validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/
  validates_length_of :password, minimum: 6

  delegate :username, :email, :password, :password_confirmation, to: :user
  delegate :twitter_name, :github_name, :bio, to: :profile

  def user
    @user ||= User.new
  end

  def profile
    @profile ||= user.build_profile
  end

  #...
end

应用/控制器/ users_controller.rb

class UsersController < ApplicationController
  def new
    @signup_form = SignupForm.new
  end

  def create
    @signup_form = SignupForm.new
    if @signup_form.submit(params[:user])
      session[:user_id] = @signup_form.user.id
      redirect_to @signup_form.user, notice: "Thank you for signing up!"
    else
      render "new"
    end
  end

  def show
    @user = current_user
  end
end

我没有看到如何传递模型的ID并指定变量。

有没有人有一个例子,或者可以使用剧集的代码作为起点提供?

1 个答案:

答案 0 :(得分:1)

该特定剧集将表单构建抽象为应用程序路径中的单独文件夹。您已进入views文件夹以查看其使用方式。具体而言,here

这是设置所有变量的地方,这些变量作为routes.rb file中定义的sessions/signup路由的一部分传递。

但是,典型的show操作不会有表单,因为它通常会显示与查询的记录有关的信息。 edit操作用于显示表单并传递给update操作。在该表单中,您将拥有用户信息的字段,并且您将提供一个hidden_field :id帮助程序,它将指示正在更新的用户的ID。那,或者使用routes参数并在保存来自传递的update哈希的更改之前在params操作中对其进行实例化。

但该特定项目中没有编辑/更新操作。