I'm trying to add answers to questions. Each questions has_one answer. I'm showing them on the comment page through partials except I keep getting this error:
undefined local variable or method `answer'
Here is part of my answers_controller.rb
class AnswersController < ApplicationController
before_action :set_answer, only: [:show, :edit, :update, :destroy]
def index
#question = Question.find params[:question_id]
#question.answers
end
def show
end
def new
#question = Question.find params[:question_id]
end
def edit
end
def create
#question = Question.find(params[:question_id])
#answer = #question.answers.create(answer_params)
respond_to do |format|
if #answer.save
format.html { redirect_to #comment, notice: 'Answer was successfully created.' }
format.json { render action: 'show', status: :created, location: #answer }
else
format.html { render action: 'new' }
format.json { render json: #answer.errors, status: :unprocessable_entity }
end
end
end
Here is my _question.html.erb partial where the answer partial is called:
<%=div_for(question) do %>
<div class="questioncontainer">
<p>
<%= question.body %>
<%= render :partial => #question.answers %>
<% if current_user == #comment.user %>
<div class="answercontainer">
<%= link_to 'Answer', new_question_answer_path(question)%>
</div>
</div>
</p>
<% end %>
<% end %>
Last, here is my _answer.html.erb partial:
<%=div_for(answer) do %>
<div class="questioncontainer">
<p>
<%= answer.body %>
</p>
</div>
<% end %>
Thanks for the help :)
Pass answer as local, via locals: {answer: #answer}
Use
<%= render question.answers %>
instead of
<%= render :partial => #question.answers %>
More info here: http://guides.rubyonrails.org/layouts_and_rendering.html#using-partials
Related
I'm trying to create a stock market app and I have a button that is breaking my web app. My issue is with this bit of embedded ruby on my
show.html.erb page:
<%= render #stock %>
<div>
<%= link_to "Edit this stock", edit_stock_path(#stock) %> |
<%= link_to "Back to stocks", stocks_path %>
<%= button_to "Delete this stock", #stock, method: :delete %>
</div>
This#stock.destroy line is needed for removing entries for a user. The error rails throws:
Showing C:/stockmarketapp/app/views/stocks/show.html.erb where line #9 raised:
undefined method `destroy' for #<StockQuote::Stock:0x000001f7fc0aa780 #attribution="Data provided for free by IEX (https://iexcloud.io).",
#response_code=200, #avg_total_volume=2261555,
#calculation_price="close", #change=-0.36, #change_percent=-0.00331,
#close=108.41, #close_source="official", #close_time=1654286400058,
#company_name="BlackRock Institutional Trust Company N.A. - iShares Core High Dividend ETF", #currency="USD", #delayed_price=108.4,
#delayed_price_time=1654286390674, #extended_change=0, #extended_change_percent=0, #extended_price=108.41,
#extended_price_time=1654300800004, #high=108.93, #high_source="15
minute delayed price", #high_time=1654286395170, #iex_ask_price=nil,
#iex_ask_size=nil, #iex_bid_price=nil, #iex_bid_size=nil,
#iex_close=108.43, #iex_close_time=1654286330444,
#iex_last_updated=nil, #iex_market_percent=nil, #iex_open=108.81,
#iex_open_time=1654263316934, #iex_realtime_price=nil,
#iex_realtime_size=nil, #iex_volume=nil,
#last_trade_time=1654286394157, #latest_price=108.41,
#latest_source="Close", #latest_time="June 3, 2022",
#latest_update=1654286400058, #latest_volume=876363, #low=108.25,
#low_source="15 minute delayed price", #low_time=1654273215082,
#market_cap=13133871500, #odd_lot_delayed_price=108.395,
#odd_lot_delayed_price_time=1654286390033, #open=108.33,
#open_time=1654263000128, #open_source="official", #pe_ratio=nil,
#previous_close=108.77, #previous_volume=1062893,
#primary_exchange="NYSE ARCA", #symbol="HDV", #volume=876363,
#week52_high=110.91, #week52_low=91.09,
#ytd_change=0.07801100501710605, #is_us_market_open=false>
Extracted source (around line #9):78910
<%= link_to "Edit this stock", edit_stock_path(#stock) %> |
<%= link_to "Back to stocks", stocks_path %>
<%= button_to "Delete this stock", #stock.destroy, method: :delete %>
</div>
Rails.root: C:/stockmarketapp
Application Trace | Framework Trace | Full Trace
app/views/stocks/show.html.erb:9
These are my files related to #stock and #stock.destroy:
class StocksController < ApplicationController
before_action :set_stock, only: %i[ show edit update destroy ]
before_action :correct_user, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
#api = StockQuote::Stock.new(api_key: "pk_153e93f4bce64c3d87e7d4d3510153ed")
# GET /stocks or /stocks.json
def index
#stocks = Stock.all
end
# GET /stocks/1 or /stocks/1.json
def show
#stocks = Stock.all
end
# GET /stocks/new
def new
#stock = Stock.new
end
# GET /stocks/1/edit
def edit
end
# POST /stocks or /stocks.json
def create
#stock = Stock.new(stock_params)
respond_to do |format|
if #stock.save
format.html { redirect_to stock_url(#stock), notice: "Stock was successfully created." }
format.json { render :show, status: :created, location: #stock }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #stock.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /stocks/1 or /stocks/1.json
def update
respond_to do |format|
if #stock.update(stock_params)
format.html { redirect_to stock_url(#stock), notice: "Stock was successfully updated." }
format.json { render :show, status: :ok, location: #stock }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #stock.errors, status: :unprocessable_entity }
end
end
end
# DELETE /stocks/1 or /stocks/1.json
def destroy
#stock.destroy
respond_to do |format|
format.html { redirect_to stocks_url, notice: "Stock was successfully destroyed." }
format.json { head :no_content }
end
end
def correct_user
#ticker = current_user.stocks.find_by(id: params[:id])
redirect_to stocks_path, notice: "Not Autherized to edit this stock" if #ticker.nil?
end
private
# Use callbacks to share common setup or constraints between actions.
def set_stock
#stock = Stock.find(params[:id])
end
# Only allow a list of trusted parameters through.
def stock_params
params.require(:stock).permit(:ticker, :user_id)
end
end
Stock partial:
<% #stock= StockQuote::Stock.quote(stock.ticker) %>
<div id="<%= dom_id stock %>">
<p>
<strong>Ticker:</strong>
<%= #stock.symbol %>
</p>
<p>
<strong>Open</strong>
$<%= #stock.open %>
</p>
<p>
<strong>Price</strong>
$<%= #stock.latest_price %>
</p>
<p>
<strong>Close</strong>
$<%= #stock.close %>
</p>
<p>
<strong>Company Name</strong>
<%= #stock.company_name %>
</p>
<p>
<strong>Primary Exchange</strong>
<%= #stock.primary_exchange %>
</p>
<p>
<strong>Volume</strong>
<%= number_with_delimiter(#stock.volume, :delimiter => ',') %>
</p>
<p>
<strong>Market Cap</strong>
$<%= number_with_delimiter(#stock.market_cap, :delimiter => ',') %>
</p>
</div>
Github Repo: https://github.com/Maikkeru/Stockmarketapp
I assume that am wielding the stock object incorrectly but I don't know where that slipup is occurring. Thanks for your time.
I am trying to improve an exercice that I did on treehouse, the idea was to remake a little version of facebook thing, where users could publish statuses.
Now I want that a user can comment any statuses... And I am kinda lost...
The idea is to have all on the same page (if possible?, like on the real facebook)
So the comment form and the "displaying" content...
I hope anyone could help me :)
This is my github repository
I think I haven't understand how to call variables from a controller to another...
If someone could explain me with very easy words ... I am not native english speaker... so sometime it's difficult..
Here are the statuses part
controllers/statuses_controller/rb
class StatusesController < ApplicationController
before_filter :authenticate_user!, only: [:new, :create, :edit, :update]
before_action :set_status, only: [:show, :edit, :update, :destroy]
def index
#statuses = Status.all
#comments = Comment.all
end
def show
#status = Status.find(params[:id])
#comments = #status.comments.all
end
def new
#status = Status.new
#comment = #status.comments.build
end
def create
#status = Status.new(status_params)
#status.user = current_user
respond_to do |format|
if #status.save
format.html { redirect_to #status, notice: 'Status was successfully created.' }
format.json { render :show, status: :created, location: #status }
else
format.html { render :new }
format.json { render json: #status.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #status.update(status_params)
format.html { redirect_to #status, notice: 'Status was successfully updated.' }
format.json { render :show, status: :ok, location: #status }
else
format.html { render :edit }
format.json { render json: #status.errors, status: :unprocessable_entity }
end
end
end
def destroy
#status.destroy
respond_to do |format|
format.html { redirect_to statuses_url, notice: 'Status was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_status
#status = Status.find(params[:id])
end
def status_params
params.require(:status).permit(:user_id, :content, :comments_attribute[:id, :status_id, :content])
end
end
models/status.rb
class Status < ActiveRecord::Base
belongs_to :user
has_many :comments
default_scope -> { order(created_at: :DESC)}
validates :content, presence: true,
length: {minimum: 2}
validates :user_id, presence: true
end
views/comments/_form.html.erb I create a render in my index below:
<% simple_form_for #status.comments do |f|%>
<%= f.input :content %>
<%= f.button :submit %>
<% end %>
view/statuses/index.html.erb
<div class="page-header">
<h1>All of the Statuses</h1>
</div>
<%= link_to "Post A New Status", new_status_path, class: "btn btn-success"%>
<br>
<br>
<% #statuses.each do |status| %>
<div class="status">
<div class="row">
<div class="col-xs-1 avatar">
<%= image_tag status.user.avatar.thumb if status.user.avatar?%>
</div>
<div class="col-xs-7">
<h4><%= status.user.full_name%></h4>
</div>
</div>
<div class="row">
<div class="col-xs-8">
<p><%= simple_format(status.content) %></p>
</div>
</div>
<div class="row">
<div class="col-xs-8">
<%= link_to time_ago_in_words(status.created_at) + " ago", status %>
<% if status.user == current_user %>
<span class="admin">
| <%= link_to "Edit", edit_status_path(status) %> |
<%= link_to "Delete", status, method: :delete, data: {confirm: "Are you sure?"} %>
</span>
<% end %>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<p>Comments</p>
<% #comments.each do |comment| %>
<%= comment.content %>
<% end %>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<%= render "comments/form" %>
</div>
</div>
</div>
Now the comments part:
model/comment.rb
class Comment < ActiveRecord::Base
belongs_to :status
belongs_to :user
end
controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
#comment = Comment.new(params_comment)
end
def index
#statuses = Status.all
#comments = Comment.all
#comment = Comment.find_by(params[:id])
end
private
def params_comment
params.require(:comment).permit(:content)
end
end
routes.rb
resources :statuses do
resources :comments
end
user.rb
that's a part of what I have in there
has_many :statuses
has_many :comments
your comments creation method should look like this:
#status = Status.find(params[:status_id])
#comment = #status.comments.create(comment_params)
#comment.user_id = current_user.id if current_user
#comment.save
I'm trying to use an if else statement in show.html.erb in the Assignment to check if a record in Bid exists. But I encountered a syntax error "SyntaxError in AssignmentsController#show" that occurs on the first line of the code below:
<%= if Bid.exists?(user_id: current_user.id, assignment_id: #assignment.id) %>
<p>it exists</p>
<%= else %>
<p>it doesn't exists</p>
The following is the entire file Assignment/show.html.erb:
<p id="notice"><%= notice %></p>
<p>
<strong>Assignment:</strong>
<%= #assignment.assignment %>
</p>
<p>
<strong>Education:</strong>
<%= #assignment.education.education %>
</p>
<p>
<strong>Subject:</strong>
<%= #assignment.subject.subject %>
</p>
<p>
<strong>Gender prefer:</strong>
<%= #assignment.gender_prefer %>
</p>
<p>
<strong>Timeslot:</strong>
<%= #assignment.timeslot %>
</p>
<p>
<strong>Duration:</strong>
<%= #assignment.duration %>
</p>
<p>
<strong>Budget:</strong>
<%= #assignment.budget %>
</p>
<p>
<strong>Budget unit:</strong>
<%= #assignment.budget_unit %>
</p>
<p>
<strong>Assignment info:</strong>
<%= #assignment.assignment_info %>
</p>
<p>
<strong>Assignment id:</strong>
<%= #assignment.id %>
</p>
<%= if Bid.exists?(user_id: current_user.id, assignment_id: #assignment.id) %>
<p>it exists</p>
<%= else %>
<p>it doesn't exists</p>
<%= end %>
<%= link_to "Create Bid", bids_path(:status => "Pending", :assignment_id => #assignment.id, :user_id => current_user.id), :method => :post %> |
<%= link_to 'Bid', {controller: "bids", action: "new", id: #assignment.id} %> |
<%= link_to 'Bid', bid_path, method: :post %> |
<%= link_to 'Bid', edit_bid_path %> |
<%= link_to 'Edit', edit_assignment_path(#assignment) %> |
<%= link_to 'Back', assignments_path %>
The following is the entire file assignments_controller.rb:
class AssignmentsController < ApplicationController
before_action :authenticate_user!
before_action :set_assignment, only: [:show, :edit, :update, :destroy]
# GET /assignments
# GET /assignments.json
def index
#assignments = Assignment.all
end
# GET /assignments/1
# GET /assignments/1.json
def show
end
# GET /assignments/new
def new
#assignment = Assignment.new
end
# GET /assignments/1/edit
def edit
end
# POST /assignments
# POST /assignments.json
def create
#assignment = Assignment.new(assignment_params)
respond_to do |format|
if #assignment.save
format.html { redirect_to #assignment, notice: 'Assignment was successfully created.' }
format.json { render :show, status: :created, location: #assignment }
else
format.html { render :new }
format.json { render json: #assignment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /assignments/1
# PATCH/PUT /assignments/1.json
def update
respond_to do |format|
if #assignment.update(assignment_params)
format.html { redirect_to #assignment, notice: 'Assignment was successfully updated.' }
format.json { render :show, status: :ok, location: #assignment }
else
format.html { render :edit }
format.json { render json: #assignment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /assignments/1
# DELETE /assignments/1.json
def destroy
#assignment.destroy
respond_to do |format|
format.html { redirect_to assignments_url, notice: 'Assignment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_assignment
#assignment = Assignment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def assignment_params
params.require(:assignment).permit(:assignment, :education_id, :subject_id, :gender_prefer, :timeslot, :duration, :budget, :budget_unit, :assignment_info)
end
end
I've tried simple if else statements which stills returns an error:
<%= if 1 > 0 %>
<p>it exists</p>
<%= else %>
<p>it doesn't exists</p>
<%= end %>
You must not put the = sign in your erb tags with if, else or end. Try something like this :
<% if 1 > 0 %>
<p>it exists</p>
<% else %>
<p>it doesn't exists</p>
<% end %>
<%= %> will print the result of your line into the generated html. So for all the lines that you don't want to print (like the if , else or for statements, and the end too), use <% %> instead.
If you want more details on erb tags, there is this this SO answer : What is the difference between <%, <%=, <%# and -%> in ERB in Rails?
you are not allowed to add = with if.
Use if like this
<% if 1 > 0 %>
<p>it exists</p>
<% end %>
I'm trying to create a has-many association within a ruby on rails app where a user has-many goals and a goal has-many steps
I can't seem to figure out how to link the creation of a Step for a certain Goal. I've been playing around with it for a while and looking around on here but haven't found a solution.
Below are my Goal_controller, Step_Controller, Step form, and Goal form
Goal Controller:
class GoalsController < ApplicationController
before_action :set_goal, only: [:show, :edit, :update, :destroy]
before_filter :authorize
# GET /goals
# GET /goals.json
def index
#goals = Goal.all
end
# GET /goals/1
# GET /goals/1.json
def show
#goal = Goal.find(params[:id])
session[:current_goal] = #goal.id
end
# GET /goals/new
def new
#goal = Goal.new
end
# GET /goals/1/edit
def edit
end
# POST /goals
# POST /goals.json
def create
#goal = current_user.goals.new(goal_params)
respond_to do |format|
if #goal.save
format.html { redirect_to #goal, notice: 'Goal was successfully created.' }
format.json { render :show, status: :created, location: #goal }
else
format.html { render :new }
format.json { render json: #goal.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /goals/1
# PATCH/PUT /goals/1.json
def update
respond_to do |format|
if #goal.update(goal_params)
format.html { redirect_to #goal, notice: 'Goal was successfully updated.' }
format.json { render :show, status: :ok, location: #goal }
else
format.html { render :edit }
format.json { render json: #goal.errors, status: :unprocessable_entity }
end
end
end
# DELETE /goals/1
# DELETE /goals/1.json
def destroy
#goal.destroy
respond_to do |format|
format.html { redirect_to goals_url, notice: 'Goal was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_goal
#goal = Goal.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def goal_params
params.require(:goal).permit(:Goal, :Description, :Date, :DueDate, :user_id)
end
end
Step Controller:
class StepsController < ApplicationController
#before_action :set_step, only: [:show, :edit, :update, :destroy]
before_filter :authorize
# GET /steps
# GET /steps.json
def index
#steps = Goal.find(params[:goal_id]).steps.all
end
def new
#step = Goal.find(params[:goal_id]).steps.new
end
# GET /steps/1
# GET /steps/1.json
def show
end
# GET /steps/1/edit
def edit
end
def create
#step = Goal.find(params[:goal_id]).steps.new(step_params)
respond_to do |format|
if #step.save
format.html { redirect_to #step, notice: 'Step was successfully created.' }
format.json { render :show, status: :created, location: #step }
else
format.html { render :new }
format.json { render json: #step.errors, status: :unprocessable_entity }
end
end
redirect_to(goal_steps_url(#goal))
end
def update
#step.update(step_params)
respond_to do |format|
if #step.update(step_params)
format.html { redirect_to #step, notice: 'Step was successfully updated.' }
format.json { render :show, status: :ok, location: #step }
else
format.html { render :edit }
format.json { render json: #step.errors, status: :unprocessable_entity }
end
end
end
# POST /steps
# POST /steps.json
def destroy
#step.destroy
respond_to do |format|
format.html { redirect_to steps_url, notice: 'Step was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_step
#step = Goal.find(params[:goal_id]).Step.find(params[:id])
end
def step_params
params.require(:step).permit(:requirement, :completionTime, :goal_id)
end
end
Step Form:
<%= form_for(#step) do |f| %>
<% if #step.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#step.errors.count, "error") %> prohibited this step from being saved:</h2>
<ul>
<% #step.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :requirement %><br>
<%= f.text_field :requirement %>
</div>
<div class="field">
<%= f.label :completionTime %><br>
<%= f.number_field :completionTime %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Goal Form:
<%= form_for(#goal) do |f| %>
<% if #goal.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#goal.errors.count, "error") %> prohibited this goal from being saved:</h2>
<ul>
<% #goal.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :Goal %><br>
<%= f.text_field :Goal %>
</div>
<div class="field">
<%= f.label :Description %><br>
<%= f.text_area :Description %>
</div>
<div class="field">
<%= f.label :Date %><br>
<%= f.date_select :Date %>
</div>
<div class="field">
<%= f.label :DueDate %><br>
<%= f.date_select :DueDate %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
It looks like you will be missing your goal_id when you submit your step creation form. You will need to store it either in a hidden field in your step form, or as part of the route (e.g. POST /goals/10/steps).
I'm trying to create a basic survey app. I'm attempting to create a choice with whatever answer the user creates, but for some reason my question isn't getting set in my choice controller.
Here's my routes:
resources :questions do
resources :choices, only: [:create, :destroy]
end
My view:
<h3>Questions:</h3>
<ul><% #survey.questions.each do |question| %>
<li><p><%= question.title %></p></li>
<% choice = question.choices.build %>
<% if question.single_response == true %>
<%= form_for [question, choice] do |f| %>
<% question.answers.each do |answer| %>
<%= f.radio_button :answer_id, answer.id %> <%= answer.title %><br>
<% end %>
<%= f.hidden_field :survey_id, value: #survey.id %>
<%= f.submit %>
My set_question method in my choice controller:
def set_question
#question = Question.find(params[:question_id])
end
And then my create method:
def create
#choice = #question.choices.build(choice_params)
respond_to do |format|
if #choice.save
format.html { redirect_to surveys_path, notice: 'Choice was successfully created.' }
format.json { render action: 'show', status: :created, location: #choice }
else
format.html { render action: 'new' }
format.json { render json: #choice.errors, status: :unprocessable_entity }
end
end
end
Which is netting a nil class error.
undefined method `choices' for nil:NilClass
Rails.root: /Users/thomashammond89/SurveyMe
Application Trace | Framework Trace | Full Trace
app/controllers/choices_controller.rb:27:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"XjNNShH6jvTAcz1NQqSBU+a+2exP2STPFnja+yfbinY=",
"choice"=>{"answer_id"=>"19",
"survey_id"=>"1",
"question_id"=>"13"},
"commit"=>"Create Choice",
"question_id"=>"13"}
Which looks to me that the question_id is there in the params. Any idea why it's not getting set?
You aren't defining the instance variable #question in your create action. Try:
#question = Question.find(params[:choice][:question_id])