简体   繁体   中英

Can use Simple form for fields that doesn't exist in table?

I recently came across simple_form , which shows validation error messages for required fields, working example

Usage:

<%= simple_form_for @user do |f| %>
  <%= f.input :username %>
  <%= f.input :password %>
  <%= f.button :submit %>
<% end %>

In the above usage it only applies to User form fields (ie fields are present in table), In my rails application User form have year of birth field as dropdown and rendered using select_tag, Is it possible to show simple form error other than form elements? I want to display error for select_tag using simple_form how do i achieve it

Sirius ROR is right - but I feel like you need some more information on how they need to work:


Virtual Attributes

You need a virtual attribute, which is done using attr_accessor

attr_accessor is a ruby method for creating getter and setter methods. This basically means you're able to create a series of virtual attributes for use in your models

Virtual attributes are methods ( attributes ) you declare which don't need to be present in your database. To answer your question about birth year , you will need to do this:

#app/models/user.rb
Class User < ActiveRecord::Base
   attr_accessor :birth_year
end

This gives any User object the birth_year attribute, like this @user.birth_year


Errors

If you're looking to render errors, there are several things you need to consider:

Firstly, I think simple_form renders your errors automatically (although not sure):

This will generate an entire form with labels for user name and password as well, and render errors by default when you render the form with invalid data (after submitting for example).

Secondly, if you want to render errors by their respective fields, you need to be aware that Rails automatically wraps erroneous fields in:

<div class="field_with_errors">
    <input type="..." >
</div>

This means if you want to style this field if an error occurs, you will have to use CSS to do it.

您可以通过在模型中定义attr_accessor :birth_year来执行此操作,但是它不会将值保存到DB中,而只是进行验证。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM