2011-08-07 4 views
0

Ruby on Rails 3.0.9를 사용하고 있으며 "문의하기"양식을 직접 구현하려고합니다. 그래서 ... "문의하기"양식을 구현하기 위해 ActiveModel 사용시 문제가 발생했습니다

가 ... 내 모델 파일에 내가 가진 :

require 'active_model' 

class ContactUs 
    include ActiveModel::Conversion 
    include ActiveModel::Validations 

    attr_accessor :email, :subject, :message 

    def initialize(attributes = {}) 
    @attributes = attributes 
    end 

    validates :email, 
    :presence => true 

    validates :subject, 
    :presence => true 

    validates :message, 
    :presence => true 


    def persist 
    @persisted = true 
    end 

    def persisted? 
    false 
    end 
end 

을 ... 내보기 파일에 내가 가진 :

<%= form_for @contact_us, :url => contact_us_path do |f| %> 
    <%= f.text_field :email %> 
    <%= f.text_field :subject %> 
    <%= f.text_area :message %> 
<% end %> 

을 ... 내 라우터 파일 I에 이 :

match 'contact_us' => 'pages#contact_us', :via => [:get, :post] 

을 ... 내 컨트롤러 파일에서 내가 가진 :

class PagesController < ApplicationController 
    def contact_us 
    case request.request_method 

    when 'GET' 
     @contact_us = ContactUs.new 

    when 'POST' 
     @contact_us = ContactUs.new(params[:contact_us]) 
    end 
    end 
end 

위의 코드를 사용하여 적어도 빈 필드가있는 양식을 제출할 때 (유효성 검사를 통과하지 못하도록하기 위해 양식을 제출할 때) 양식을 다시로드하면 해당 필드가 자동 채워지지 않습니다. . 즉, 양식을 다시로드 한 후 (제출 버튼을 누른 후에 발생) 필드 값이 모두 공백 값으로 설정됩니다.

무엇이 문제인가? ActiveModel을 잘못 사용 했습니까?

+0

ActiveRecord를 확장하는 대신에 'active_model'이 필요한 이유가 있습니까? 나는 Rails에 익숙하지 않고 아직 그것을 보지 못했다. – Nic

+0

@melee 여기에서 있습니다 : https://github.com/rails/rails/blob/master/activemodel/examples/validations.rb – Backo

답변

0

는 시도 대체 할

<%= form_for @contact_us, :url => contact_us_path do |f| %> 
    <%= f.text_field :email %> 
    <%= f.text_field :subject %> 
    <%= f.text_area :message %> 
<% end %> 

<%= form_for @contact_us, :url => contact_us_path do |f| %> 
    <%= f.text_field :email, :value => @contact_us.email %> 
    <%= f.text_field :subject, :value => @contact_us.subject %> 
    <%= f.text_area :message, :value => @contact_us.message %> 
<% end %> 

편집 :

: 나는 당신이, 대량의 할당은 기능 직접 추가과 같이해야합니다 생각

def initialize(attributes = {}) 
    attributes.keys.each do |attr| 
    self.class.send(:attr_accessor, attr.to_sym) 
    instance_variable_set "@" + attr.to_s, attributes[attr.to_sym] 
    end 
end 

self.class.send(:attr_accessor, attr.to_sym)을 실제로 건너 뛰어도됩니다.

+0

그것은 작동하지 않습니다. 양식 제출시 '@contact_us = ContactUs.new (params [: contact_us])'데이터를 채우지 못하는 것 같습니다. – Backo

+0

그래서 오류 메시지는 항상 세 필드 모두에 대해 산출됩니까? –

+0

예, 그것들은 굴복되었습니다 ... 너무 많이 !!! 또한 모든 필드를 채우면 오류가 발생합니다. – Backo