Upload files to rails

Source: Internet
Author: User
2.3.3 improve "add message"
When adding a new message, we hope that users can upload images and determine whether the type of uploaded files is large or not. This is not hard to achieve in Rails. You don't need to use any plug-ins. You only need simple code to upload images! This is indeed a pleasant task for programmers.

In this section, we will improve "add a message" and introduce the implementation of Image Upload.

Modify the new. rhtml View File in the/app/views/message path. The modified code is as follows:

<Table valign = "top" width = "100%" border = "0" cellspacing = "0" cellpadding = "0">

<Tr>

<Td>

<Center>

<% = Error_messages_for 'message' %>

</Center>

<! -- Set the multipart option to true to allow file upload -->

<% = Start_form_tag ({: action => 'create',: id => @ message},: multipart => true) %>

<Table align = "center" width = "400" border = "0" cellpadding = "0" cellspacing = "0"

Bgcolor = "# BFCAE6">

<Tr>

<Td colspan = "2" id = "title"> Add a message </td>

</Tr>

<Tr>

<Td width = "15%"> <B> title </B> </td>

<Td> <% = text_field ('message', 'title',: size => "30") %> </td>

</Tr>

<Tr>

<Td width = "15%"> <B> content </B> </td>

<Td> <% = text_area 'message', 'detail', "cols" => 40, "rows" => 10%> </td>

</Tr>

<Tr>

<Td width = "15%"> <B> Texture </B> </td>

<! -- Call the file_field help method to generate a file Domain -->

<Td> <% = file_field 'message', 'picture '%> </td>

</Tr>

<Tr>

<Td colspan = "2" align = "center"> <% = submit_tag ''%> </td>

</Tr>

</Table>

<% = End_form_tag %>

</Td>

</Tr>

</Table>

The code above specifies that the multipart option value is true in the start_form_tag help method, so that the form can send file data. In addition, a file domain is generated by calling the file_field help method. The picture attribute here is only a virtual attribute, because it does not exist in the Database's messages table. This requires processing of this virtual attribute to correspond to the real attribute in the messages table. The specific implementation method is described in detail below.

The above form does not design form fields for the Message time, because we can assign values to this attribute of the Message object in a simpler way: the field name indicating the Message time in the messages table is created_at, the data type is designed as timestamp. In this way, when a record corresponding to the Message object is saved, Rails automatically assigns the current time to the created_at column without manual assignment.

In the message_controller.rb controller file, you need to modify the create method. After modification, the code snippet of this method is as follows.

Def create

# Find the User object of the current message

User = User. find (session [: user_id])

# Assign the User object to the user attribute of the Message object in the Parameter

Params [: message] [: user] = user

# Construct a Message object and use the message parameter to initialize the object

@ Message = Message. new (params [: message])

# If the Message object can be successfully saved to the database

If @ message. save

Flash [: notice] = 'message added successfully! '

# Redirect to list Action

Redirect_to: action => 'LIST'

Else

# Submit a new Action

Render: action => 'new'

End

End

In the definition of the create method, the first two statements of Code are not found in the default code generated by scaffold. This is because the user_id is a foreign key column of the messages table referring to the users table. scaffold does not automatically generate an external key column. Therefore, we need to find the User object of the Message based on session [: user_id] and assign the object to the Message object in the form parameter as a user attribute. In this way, when the Message object calls the save method to save the data to the database, the corresponding data row of the Messge object will be referred to the corresponding data row of the User instance.

In the Message Model file, redefine a picture = method. Because our new. the rhtml View File has a picture form field. After the form is submitted, the controller sends a request parameter for message [: picture]. This request parameter requires the Message class to contain a picture = method, this method is used to accept the message [: picture] request parameters.

The picture = method is used to parse the message [: picture] request parameters (the request parameter value is a file object that contains a wealth of information. The following is the picture = method code:

# The picture = method is provided to set a picture form field to multiple attributes of the Message object.

Def picture = (picture_field)

Transaction do

# If the user uploads an image

If picture_field.size> 0 then

# @ Picture_size indicates the file size of the uploaded image.

@ Picture_size = picture_field.size

# @ Picture_type indicates the file type of the uploaded image.

@ Picture_type = picture_field.content_type.chomp

# Set the picture_content_type attribute of the Message object

Self. picture_content_type = @ picture_type

# Set the picture_data attribute of the Message object

Self. picture_data = picture_field.read

End

End

End

After the picture = method is provided, the message [: picture] request parameter corresponds to the actual attributes picture_content_type and picture_data in the messages table.

Rails handles file upload very well. The file Field Parameter Value in the form is no longer a simple type value, but has been packaged into a file object. It also has size, the content_type and read Methods call these methods directly to return the file object size, file type, and binary data.

When a user adds a message, we need to perform model verification on the message object. This can be achieved by reusing the validate method in the message. rb model file. The Code is as follows:

Def validate

# Verification title cannot be blank

Errors. add ("", "title cannot be blank") if title. empty?

# Verification detail cannot be blank

Errors. add ("", "content cannot be blank") if detail. empty?

# Verify the uploaded image below

If @ picture_type! = Nil

# Verify the file type of the uploaded Image

Errors. add ("", "texture is not a valid image file") unless @ picture_type = ~ /^ Image/

End

If @ picture_size! = Nil

# Verify the file size of the uploaded Image

Errors. add ("", "The texture file is too large to exceed 50 KB") if @ picture_size> MAX_IMAGE_SIZE

End

End

In the above code, we can verify that the value of the Message title and content cannot be blank. the uploaded file type must be in the image format, the file size cannot exceed the maximum image size that can be uploaded (MAX_IMAGE_SIZE is the maximum image size that can be uploaded ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.