Reputation: 653
I'm trying to make a twitter clone where a tweet displays the username of the user next to it. however getting the above error message and highlighting the first line of my create method. any ideas on how to solve. I've done the association already. thanks
class TweetsController < ApplicationController
def index
@tweets = Tweet.all.order("created_at DESC")
@tweet = Tweet.new
end
def show
@tweet = Tweet.find(params[:id])
end
def new
# @tweet = Tweet.new
end
def create
@user = User.find(params[:id])
@tweet = Tweet.new(tweet_params)
@tweet.user = @user
if @tweet.save
redirect_to tweets_path
end
end
private
def tweet_params
params.require(:tweet).permit(:content, :user_id)
end
end
<%= simple_form_for @tweet, id: "form-submit" do |f| %>
<%= f.input :content %>
<%= f.button :submit, class: "btn btn-danger" %>
<% end %>
<% @tweets.each do |tweet| %>
<ul>
<li>
<%= tweet.content %>
<%= tweet.user.username %>
</li>
</ul>
<% end %>
Upvotes: 0
Views: 102
Reputation: 5552
By answer accepted here, most appropriate change could be:
def new
@tweet = current_user.tweets.new
end
def create
@tweet = Tweet.new(tweet_params)
if @tweet.save
redirect_to tweets_path
end
end
nothing else was needed to be done.
Upvotes: 0
Reputation: 27
You are defining tweet.users after using tweet_params, since for tweet_params the user is not defined, that's why you are getting this error.
Upvotes: 0
Reputation: 2004
params
hash does not contain id
, because of that you are getting this error.
Just modify your create action as
def create
@user = current_user
@tweet = Tweet.new(tweet_params)
@tweet.user = current_user
if @tweet.save
redirect_to tweets_path
end
end
Or
instead of above you can also pass an user_id
from the form.
<%= simple_form_for @tweet, id: "form-submit" do |f| %>
<%= f.input :content %>
<%= f.hidden_field :user_id, value: current_user.try(:id) %>
<%= f.button :submit, class: "btn btn-danger" %>
<% end %>
then modify create action as
def create
@tweet = Tweet.new(tweet_params)
if @tweet.save
redirect_to tweets_path
end
end
NOTE: Assuming that you are using devise gem for authentication
Upvotes: 0