I am making a portfolio page in rails. On the front page I have an "About" section where I have a personal description of myself. I want to be able to change this dynamically (not hard-coded html).
I would like to have the description be a text variable or string that I can modify through a form in the view section.
Questions 1. How should I declare this variable in the controller? 2. How do I access and change it from the form in the view? 3. Is there a better solution to my problem?
The only way to do this is to send the updated values to your controller. You need to have a form
on your portfolio page:
#config/routes.rb
resources :users do
resources :portfolios #-> url.com/users/:user_id/portfolios/:id
end
#app/controllers/portfolios_controller.rb
class PortfoliosController < ApplicationController
def show
@user = User.find params[:user_id]
end
end
#app/controllers/users_controller.rb
class UsersController < ApplicationController
def update
@user = User.find params[:id]
@user.update user_params
end
private
def user_params
params.require(:user).permit(:about)
end
end
#app/views/portfolios/show.html.erb
<%= form_for @user do |f| %>
<%= f.text_field :about %>
<%= f.submit %>
<% end %>
Without any more context, that's the best I can give.
You will need to connect a database to store and retrieve dynamic stuff. You can access a variable in views if you define it with @
like;
@about= Me.last.about
where Me could be your model that the information is saved in and Me.last would be the instance of that model. You can update this information by updating the model like
Me.last.update_attributes :about=> params[:about]
where params[:about]
would be the params from the field in the form.
I would recommend following a guide so you get a complete solution. Below I have the major steps a user would take to update some content. This code is not a complete solution.
Your form would submit the updated content to another controller action (through another route).
<%= form_for @user do |f| %>
In that controller, you would store the content (usually in the database).
def update
@user = User.find(params[:id])
@user.update(user_params)
redirect_to :back
end
The original controller action would have a variable that got the content from the place you stored it
def show
@user = User.find(params[:id])
end
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.