Hey all,(im a beginner in rails)
i’ve created a controller that look like that:
class HomeController < ApplicationController
def homepage
end
def showmsg
@postword = params[:p]
end
end
the showmsg view looks like that:
<%= @postword %>
and my homepage view looks like that:
<%= form_tag( {:controller => 'home', :action => 'showmsg'}, :method => "post") do %>
<%= text_field_tag(:p,@postword) %>
<%= submit_tag("post") %>
<% end %>
now i have a form that i can write something in it and it will show on the showmsg view.
i created a model with the param :posts with a :description “text” field too.
MY QUESTION is how do i implement the model in the code so any thing i write will be in a list with the things i wrote before, because now (obviously) anything if i write something its deleting the one i wrote before.
thank you all!
I would argue that you’re approach is not very rail’s like… so if you’re learning rails… you’re learning it wrong.
Make a Model. Call it “Message”:
remember to migrate (hopefully you have your databases setup properly):
Then in your controller, when you post, you can create message like this:
This will create the message in the database, and then it will get all the messages out of the database and put them into @messages.
You need to edit your form so that it uses
form_for. You need to pass it@message, which is an instance ofMessage.newthat your first controller action created. You should call thisnewIn your create.erb.html file, you show all the messages like this:
I actually wouldn’t recommend showing all the messages in the create action – it should really happen in the
indexaction and you should redirect… but we need to keep this simple. Just google this or watch some of Ryan’s screencasts and you’ll get it.And you’re done. This is the “Rails Way” to do things. It’s best to learn it the way they want you to learn it.
I would also commend that you format your code properly by indenting, and start naming your methods to be real english. For example,
showmsgis bad andshow_messageis a lot better.If all of this is totally confusing, then just create a new project, and then type:
It will basically build the application you want and a lot more. You can just read the code and see how they did it.
Hope it helps.