ruby-on-rails - 我是否正确使用了 rails 表单?

标签 ruby-on-rails ruby ruby-on-rails-3 refactoring

我觉得我不知道我在做什么..我有一个模糊的想法。我希望到目前为止我做得很好。

如果您能以任何方式重构它,我们将不胜感激。

我注意到它做错的一件事是它不会加载以前提交的正确选项,如果有错误并且它发布到相同的 URL。文本输入似乎加载了以前的值,但选择和单选按钮在每次提交时都重置为默认值。

资源 Controller #new

 def new
    @resource = Resource.new
    @title = "Submit Resource"
    @categories = Category.all
 end

ResourcesController#create(注意我在两者中都有@categories = Category.all...根据DRY我不确定它应该去哪里,或者它只适用于第一个表单提交。

  def create
    @title = "Submit Resource"
    @categories = Category.all

    @resource = Resource.new(params[:resource])

    category_ids = @categories.map { |c| c[1] }

    if @resource.valid? and category_ids.include? params[:category_id]
      @resource.cost = params[:cost]
      @resource.category_id = params[:category_id]
      @resource.save
      redirect_to root_url
    else
      render :action => :new
    end 
  end

Resource.rb(模型)

# == Schema Information
#
# Table name: resources
#
#  id          :integer         not null, primary key
#  upvotes     :integer         default(0)
#  downvotes   :integer         default(0)
#  url         :string(255)
#  title       :string(255)
#  cost        :integer         default(0)
#  description :text
#  flags       :integer
#  category_id :integer
#  user_id     :integer
#  created_at  :datetime        not null
#  updated_at  :datetime        not null
#

class Resource < ActiveRecord::Base

  belongs_to :category
  belongs_to :user
  has_many :favorites
  has_many :resource_tags
  has_many :tags, :through => :resource_tags

  attr_accessible :url, :title, :cost, :description, :category_id, :user_id

  # Pseudo-Enum
  COST = [:free, :paid, :both]

  url_regex = /^(?:http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?$/ix

  validates :url,         :presence => true,
                          :format   => { :with => url_regex, 
                                         :message  => "must be valid"},
                          :uniqueness => { :case_sensitive => false,
                                           :message => "has already been submitted"}
  validates :title,       :presence => true,
                          :length   => { :within => 6..75 }
  validates :cost,        :presence => true
  validates :description, :presence => true,
                          :length   => { :within => 25..200 }
  validates :category_id, :presence => true,
                          :format   => { :with => /\d+/ }
  validates :user_id,     :presence => true,
                          :format   => { :with => /\d+/ }

  def cost
    COST[read_attribute(:cost)]
  end

  def cost=(value)
    write_attribute(:cost, COST.index(value.downcase.to_sym))
  end

  def category_id
    read_attribute(:category_id).to_i
  end

  def category_id=(value)
    write_attribute(:category_id, value.to_i)
  end

end

我的资源 View 文件#new form

  <div class="field">
    <%= f.label :category %>
    <%= select_tag(:category_id, options_for_select(@categories.map {|c|[c.name, c.id]})) %> 
  </div>

最后一个问题:我还没有使用过 user_id 字段。这将从设计中提取并将用户与提交的资源相关联。但是我如何在不进行某种输入(例如隐藏输入)的情况下分配它。这会在 Controller 的幕后发生吗?

最佳答案

最后一个问题:

设计添加一个 current_user 方法,它是登录用户。因此,如果用户拥有多个资源,您可以执行以下操作:

@resource = current_user.resources.new(params[:resource])

第一个问题:

当呈现表单时,它是基于@resource 和@categories 变量完成的。当您发布表单时,会调用创建操作来创建一个新的@resource。如果由于某种原因保存失败,则使用新的@resource 变量重新呈现表单。您遇到的问题是当您再次显示表单时未设置@resource.category。所以您必须在 is_valid 之前执行此操作?检查。

 def create
    @title = "Submit Resource"
    @categories = Category.all

    @resource = Resource.new(params[:resource])
    @resource.category = Category.find(params[:category_id])

    if @resource.valid? # won't be valid if there is no category found.
      @resource.cost = params[:cost]
      @resource.save
      redirect_to root_url
    else
      render :action => :new
    end 
  end

但真正的问题在于您的表单。它应该将 category_id 嵌套在资源参数中,以便在执行 Resource.new(params[:resource]) 时设置类别。

检查控制台中的 POST 请求正文或其他内容,看看它是否嵌套在资源中。我不知道它的确切语法,但如果您更改它,您可以删除 @resource.category = Category.find 行。

关于ruby-on-rails - 我是否正确使用了 rails 表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9639721/

相关文章:

ruby-on-rails - 在设计注册中保留查询字符串

ruby - 如何获取请求时区?

ruby-on-rails-3 - 使用 Rails 针对 Postgres Follower(数据库镜像)运行分析

ruby-on-rails-3 - Rails 3 - 验证和 :before_filter

ruby - 如何将新的自定义资源添加到路由 Rails 3

ruby-on-rails - Ruby/Rails - 文件命名约定和处理大写模型名称(即 CSV 与 Csv)

javascript - 单击时渲染部分表单,Rails

ruby-on-rails - 如何在测试 rails 中验证包含 true 或 false 工作?

Ruby Net::SCP 下载要求输入密码然后失败

ruby-on-rails - 使用 -Ilib 和 -Itest 运行 Rails 单元测试有什么区别?