简体   繁体   中英

rails custom html elements form

I am new in Rails and i've searched around the web and books but I couldnt find how to make custom forms when working with rails.. what happens is that I am used to write my own HTML tags and I confortable with that. I dont like to use libs like JSF (from JAVA) that writes html components for me and I dont want that rails write it for me, except for simple tags like

text_field(:post, :title, :size => 20)
# => <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />

so.. how can I do that.. for example: I would like to write by myself

<input type="text" class="myclass" data="mydata" name="how-to-get-the-attribute-name-with-rails" value="how-to-get-value-with-rails" />

how can I do that?

If you want more control over the html you are creating, you can also use a content_tag

content_tag :input, "label_name", class: "myclass", data: "mydata", name: "how-to-get-the-attribute-name-with-rails", value: "how-to-get-value-with-rails"

You can supplement any html element tag for :input . So if you want a div instead, use :div etc...

As you have written above, The name of any form field in rails is in the following format

name = 'post[name]' i.e. model_name[attribute_name]

So your params hash will contain :post => {:name => value} which allows you to use mass-assignment. But if you want to get some extra parameters from the form you can directly include them in the form and give them any name as you want. It will be available in your params hash.


You can get value easily using value = <%= @object.attribute_name. %> value = <%= @object.attribute_name. %> I am not sure if you wanted to know this or something else. Let me know if you need more help.

You can simply write html inside a Rails form, so

<input type="text" class="myclass" data="mydata" name="how-to-get-the-attribute-name-with-rails" value="how-to-get-value-with-rails" />

is perfectly valid, but note that you should use the names and id's in correct way to automatically bind them to your back end controller.

After all, what text_field(:post, :title, :size => 20) does is it convert the parameters to pure HTML (we call them helper methods in Rails).

Read here for formhelper options (using helpers will keep your code clean).

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