Rails form is not saving input to the database - ruby-on-rails

I making a very simple RESTful app and when I input a string into the form field and submit it, the database hold NULL instead of the input string.
Here is my controller:
def create
#song = Song.create(params[:title])
flash[:success] = "You have successfully created a new project!"
redirect_to "/songs/#{#song.id}"
end
Here is my form in the new.html.erb file:
<%= form_for(#song) do |f| %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<br>
<% end %>

If you are using rails < 4 then you should have
def create
#song = Song.create(params[:song])
flash[:success] = "You have successfully created a new project!"
redirect_to #song
end
and if you are using rails > 4 then you should have
def create
#song = Song.create(song_params)
flash[:success] = "You have successfully created a new project!"
redirect_to #song
end
private
def song_params
params.require(:song).permit(:title)
end

Related

Url changed when submit and surrounding issues

i'm newbie in Ruby on rails.
I'm doing CRUD for Articles and have a question: how to keep url and data's form when i create or update a article but it invalid validate?
And if they resolved, how to keep _form.html.erb to use for create and edit view.
I tried some solution in stackoverflow but there are no solution resolved all my problems above.
Here is new article view:
https://ibb.co/bdm4Hxj
You see, url change from /articles
https://ibb.co/wQ6Vxpz
inspect, we see action: /articles, method: post
https://ibb.co/LPJzvLr
and routes in rails:
https://ibb.co/rs1T1PY
_form.html.erb for create and edit view:
<%= form_for #article, html: {class: "form-horizontal"}, local: true do |f| %>
<div class="form-group">
<%= f.label :title, "Title", class: "col-md-2 control-label" %>
<div class="col-md-6">
<%= f.text_field :title, class: "form-control" %>
</div>
</div>
<div class="form-group">
<%= f.label :text, "Text", class: "col-md-2 control-label" %>
<div class="col-md-6">
<%= f.text_area :text, class: "form-control"%>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-4">
<a class="btn btn-success" href="<%= articles_path %>">Back</a>
<%= f.submit action_name.capitalize, class: "btn btn-success" %>
</div>
</div>
<% end %>
My ArticlesController:
class ArticlesController < ApplicationController
def index
#articles = Article.all
end
def new
#article = Article.new
end
def show
#article = get_by(:id)
end
def create
#article = Article.new(article_params)
if #article.save
flash[:success] = 'Create success!'
redirect_to articles_path
else
flash[:warning] = 'Something went wrong!'
render :new
end
end
def edit
#article = get_by(:id)
end
def update
#article = get_by(:id)
if #article.update(article_params)
flash[:success] = 'Update success!'
redirect_to articles_path
else
flash[:warning] = 'Update failed!'
render :edit
end
end
def destroy
#article = get_by(:id)
if #article.destroy
flash[:success] = 'Delete success!'
redirect_to articles_path
else
flash[:warning] = 'Delete failed!'
render :new
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
def get_by(id)
Article.find(params[id])
end
end
Thank you and sorry because of my bad english!
Your examples look pretty much what comes out of a scaffold, which is not too bad a start when learning how things can work (rails g scaffold article).
The relevant controller and views are then set up to do exactly what you are asking for: The controller holds a local variable (#article) ready for the view (ultimately _form.erb), whether or not the objects data is valid.
I wonder: What exactly happens? When you save with invalid data, the form should show up with the invalid data still in place. If you compare your form with the one that is created by the scaffold, you will notice that some output regarding validation errors is missing in your example. Try to add it, or start from scratch to see how it looks like.
When the data is valid and you still want the controller to show the user the form after hitting save, instead of redirect_to ... just render :edit.

Cannot enter simply form information into SQLite DB (Rails)

So, I'm running into a fairly simple problem, where I cannot enter some simple form values into my SQLite DB (Rails).
Interestingly, the code doesn't fail - I submit the form, and am redirected successfully to the correct URL - and a record IS inserted into the DB, but the columns "name, type and user_id" are not filled with anything. To clarify, the columns are blank, for that new record.
If I comment out the code in the "create" and simply spit out the params (render plain: params[:plan].inspect) I do see all the correct parameters filled out, so I have a feeling there must be something wrong in the line:
#plan = Plan.new(params[:plan])
I'm really stuck here, any guidance would be much appreciated!
The create form
<h1> Create a new plan </h1>
<%= form_for :plan, url: plans_path do |f| %>
<p>
<%= f.label :name %><br>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :type %><br>
<%= f.text_field :type %>
</p>
<%= f.hidden_field :user_id, :value => current_user.id %>
<p>
<%= f.submit %>
</p>
<% end %>
plans_controller.rb
class PlansController < ApplicationController
def index
#plans = Plan.all
end
def show
#plan = Plan.find(params[:id])
end
def new
#plan = Plan.new
end
def create
#render plain: params[:plan].inspect
params.permit!
#plan = Plan.new(params[:plan])
if #plan.save
redirect_to #plan
else
redirect_to dashboard_path, :notice => "Plan NOT Created!"
end
end
end
The Model
class Plan < ActiveRecord::Base
end
Edit the plans_controller.rb:-
def create
#render plain: params[:plan].inspect
#plan = Plan.new(plan_params)
if #plan.save
redirect_to #plan
else
redirect_to dashboard_path, :notice => "Plan NOT Created!"
end
end
private
def plan_params
params.require(:plan).permit(:name,:type,:user_id)
end
Change the field name type as :-
rails g migration rename_fields_in_plans
class RenameFieldsInPlans < ActiveRecord::Migration
def change
rename_column :plans, :type, :plan_type
end
end
Then run the command:-
rake db:migrate

rails 4.0 undefined method

I have an Opportunity model that has Activity as a nested resource. on my opportunities/show page, I have a list of activities for that opportunity and a form to add new activities. When I click "add activity" I get:
undefined method `activities' for nil:NilClass
Here is the error source:
# POST /activities.json
def create
#activity = #opportunity.activities.new(activity_params)
if #activity.save
redirect_to #opportunity, notice: 'Activity has been added'
else
I defined my Opportunity model as having many Activities and that my Activities belongs to an Opportunity. Here are the relevant parts of my Activity controller:
def create
#activity = #opportunity.activities.new(activity_params)
if #activity.save
redirect_to #opportunity, notice: 'Activity has been added'
else
redirect_to #opportunity, alert: 'Unable to add Activty'
end
end
And here is my views/activities/new code
<%= form_for ([#opportunity, #opportunity.activities.new]) do |f| %>
<div class="field">
<%= f.label "Date Assigned" %> <br />
<%= f.text_field :date_assigned %>
</div>
<div class="field">
<%= f.label "Date Due" %> <br />
<%= f.text_field :date_due %>
</div>
<div class="field">
<%= f.label "Description" %> <br />
<%= f.text_field :description %>
</div>
<div class="field">
<%= f.label "Status" %> <br />
<%= f.text_field :status %>
</div>
<div class="actions">
<%= f.submit 'Add' %>
</div>
<% end %>
My routes:
resources :opportunities do
resources :activities
end
thank you!!
Your #opportunity is undefined(nil) in the block.
You must get #opportunity prior to building activities on it as :
#opportunity = Opportunity.find(params[:opportunity_id])
(Reason for :opportunity_id : Since this is ActivityController and your model is nested, by conventional nested RESTful resources (as specified in your routes), the parameter is automatically assigned as model_id => opportunity_id)
Changed code:
def create
#opportunity = Opportunity.find(params[:opportunity_id])
#activity = #opportunity.activities.new(activity_params)
if #activity.save
redirect_to #opportunity, notice: 'Activity has been added'
else
Also, it is recommend to use build instead of new while building object for relations.
Try using build instead of new.
#activities = #oportunities.activities.build(activity_params)
That should work
Edit:
You didn't find for #oportunities before the build :P
def create
#oportunities.find(params[:id])
#activity = #opportunity.activities.new(activity_params)
if #activity.save
redirect_to #opportunity, notice: 'Activity has been added'
else
redirect_to #opportunity, alert: 'Unable to add Activty'
end
end

Redirect to show in another controller (Rails)

I have a form that allows the user to Post in the a group Show method. Upon posting, I want to redirect to the same page showing the new post. I'm using the following, but I get the error below. I'm not sure why #group is nil, because I've defined it in the show of my group controller.
No route matches {:id=>nil} missing required keys: [:id]
for
redirect_to group_path(#group)
<%=form_for([#post]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class = "field">
<%= f.label :event_name %>
<%= f.collection_select(:event_id, #events, :id, :title) %>
</div>
<div class = "field">
<%= f.text_area :comment, placeholder: "New Post..." %>
</div>
<%= f.hidden_field :user_id, value: current_user.id %>
<%=f.submit "Submit", class: "btn btn-large btn-primary" %>
<%end%>
class PostsController < ApplicationController
def create
if #post = Post.create(post_params)
flash[:success] = "Post Created!"
redirect_to group_path(#group)
else
redirect_to group_url
flash[:alert] = "Sorry - Post not created."
end
end
end
def show
#event = #group.events.build
#post = Post.new
#events = #group.events.includes(:posts)
#group = Group.find(params[:id])
end
In your create action you attempt to use the #group instance variable. You haven't defined it in the create action so you'll need to create it there if you want to use it. Since the call to create is in a separate request cycle the instance variables you defined in the show action are not available.
Update:
To get the group if you have an event_id and event belongs_to :group you would do:
event = Event.find(event_id)
#group = event.group
Set #group in create action. You have not assigned any value to #group there which is why you are getting error.
EDIT
As per your comment A Group has_many events so you can find the group as below:
#group = Event.find(params[:event_id]).group

Rails: Adding to model after user submits form

In my Rails 3.2 project, I have a form to create a new post in new.html.erb in app/views/posts/
<%= form_for(#post) do |post_form| %>
...
<div class="field">
<%= post_form.label :title %><br />
<%= post_form.text_field :title %>
</div>
<div class="field">
<%= post_form.label :content %><br />
<%= post_form.text_field :content %>
</div>
<div class="actions">
<%= post_form.submit %>
</div>
<% end %>
Then the create function in posts_controller.rb
def create
#post = Post.new(params[:post])
if #post.save
format.html { redirect_to #post }
else
format.html { render action: "new" }
end
end
When the user submits a post, the title and content of the post are added to the Post model. However, I also want to add to another field of that post. For the field random_hash (which the user doesn't get to specify), I want to make it a string of 8 lowercase letters, the first 2 of which are the first 2 letters of the title, and the last 6 are random lowercase letters. How can I do that?
def create
#post = Post.new(params[:post])
#post.random_hash = generate_random_hash(params[:post][:title])
if #post.save
format.html { redirect_to #post }
else
format.html { render action: "new" }
end
end
def generate_random_hash(title)
first_two_letters = title[0..1]
next_six_letters = (0...6).map{65.+(rand(25)).chr}.join
(first_two_letters + next_six_letters).downcase
end
Put that in your controller. You obviously have to have random_hash attribute for Post model to work.
I am using Kent Fredric's solution to generate six random letters.

Resources