gpt4 book ai didi

ruby-on-rails - Rails 4 - 在没有数据库的情况下验证模型

转载 作者:搜寻专家 更新时间:2023-10-30 20:02:10 24 4
gpt4 key购买 nike

我已遵循本教程并尽我所能为 Rails 4 塑造它。

http://railscasts.com/episodes/219-active-model?language=en&view=asciicast


class Contact
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming

validates :name, :email, :phone, :comment, :presence => true

def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end

def persisted?
false
end

private
# Using a private method to encapsulate the permissible parameters is just a good pattern
# since you'll be able to reuse the same permit list between create and update. Also, you
# can specialize this method with per-user checking of permissible attributes.
def contact_params
params.require(:contact).permit(:name, :email, :phone, :comment)
end
end

在我的 Controller 中:

class ContactController < ApplicationController
def index
@contact = Contact.new
end

def create
@contact = Contact.new(params[:contact])
if @contact.valid?
# Todo send message here.
render action: 'new'
end
end
end

在我看来:

<%= form_for @contact do |f| %>
<%= f.label :name %>:
<%= f.text_field :name %><br />

<%= f.label :email %>:
<%= f.text_field :email %><br />

<%= f.submit %>
<% end %>

我收到此异常消息:

undefined method `name' for #<Contact:0x007fd6b3bf87e0>

最佳答案

您必须将它们声明为属性。

attr_accessor :name, email, :phone, :comment

关于ruby-on-rails - Rails 4 - 在没有数据库的情况下验证模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16865821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com