How can i put the id inside of my params?
so far i am doing like this:
def post_params
params.require(:post).permit(:name, :country, user_id:params[:user_id], live_id: live.id)
end
I want to put params[:user_id] and live.id inside of params
You can set live id from your controller actions instead of using param method. Please follow below steps. Hope it will be useful for you.
def create
live = Live.create()
# Set live id inside post_params
#post = Post.new(post_params.merge!(live_id: live.id))
# If you have current_user present you can set user_id as well using below way
# #post = Post.new(post_params.merge!(user_id: current_user.id, live_id: live.id))
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully
created.' }
format.json { render :show, status: :created, location:
#post }
else
format.html { render :new }
format.json { render json: #post.errors, status:
:unprocessable_entity }
end
end
end
def post_params
params.require(:post).permit(:name, :country, :user_id, :live_id)
end
Related
I am getting error - undefined method collect for nil:NilClass, but I am able to render option list from another database table, and also able to save data in stage table but not able to update it.
I am rendering option list form responsibility table in stage form field responsibility option and saves that option into stage table.
stages_controller.rb
def index
redirect_to project_path(#project)
end
def show
end
def new
#stage = Stage.new
#responsibilities = #project.responsibilities
end
def edit
end
def create
#responsibilities = #project.responsibilities
#stage = #project.stages.build(stage_params)
respond_to do |format|
if #stage.save
format.html { redirect_to project_path(#project), notice: 'Stage was successfully created.' }
format.json { render :show, status: :created, location: #stage }
else
format.html { render :new }
format.json { render json: #stage.errors, status: :unprocessable_entity }
end
end
end
def update
#responsibilities = #project.responsibilities
respond_to do |format|
if #stage.update(stage_params)
format.html { redirect_to project_stages_url, notice: 'Stage was successfully updated.' }
format.json { render :show, status: :ok, location: #stage }
else
format.html { render :edit }
format.json { render json: #stage.errors, status: :unprocessable_entity }
end
end
end
def destroy
#stage.destroy
respond_to do |format|
format.html { redirect_to project_stages_url, notice: 'Stage was successfully deleted.' }
format.json { head :no_content }
end
end
private
def set_stage
#stage = Stage.find(params[:id])
end
def find_project
#project = Project.find(params[:project_id])
end
your edit method is empty, so #responsibility has no content (null), you can put some code for example (from your other method)
def edit
#project = Project.find(params[:id])
#responsibilities = #project.responsibilities
...
end
The issue here is that #responsibilities is not defined in your partial.
You should pass the local variable to the partial like this -
<%= render partial: "form", locals: {responsibilities: # responsibilities} %>
and then you can use responsibilities inside the form partial
More about passing variable to partials
Hello I am building ROR Survey application for survey. I am having a problem of saving multiple objects into my database.My paramters after submission look all good but instead get an error of:
undefined methodpermit' for #Array:0x00007ff29d873010`
My parameters look like
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"vdUPSIU43ex1Wx3qZB4Xr6qNEaG0FbEyK2tkJ9OCcAtxK3jHe5lKVohS9JFOdpx/cISwIvzAKTRGw5zxUUS4QA==",
"survey_response"=>[
{"user_id"=>"1", "survey_question_id"=>"22", "answer"=>"Hello"},
{"user_id"=>"1", "survey_question_id"=>"23", "answer"=>"Hello"}],
"commit"=>"Create Survey response"
}
My survey_response_params methods is
def survey_response_params
params.require(:survey_response).permit(:answer, :survey_question_id, :user_id, :survey_answer_id)
end
My controller looks like :
class SurveyResponsesController < ApplicationController
def index
#survey_responses = SurveyResponse.all
end
def show
end
def new
#survey_response = SurveyResponse.new
#survey = Survey.find(1)
#survey_questions = #survey.survey_questions
end
def edit
#survey = Survey.find(1)
#survey_questions = #survey.survey_questions
end
def create
#survey_response = SurveyResponse.new(survey_response_params)
respond_to do |format|
if #survey_response.save
format.html { redirect_to #survey_response, notice: 'Survey response was successfully created.' }
format.json { render :show, status: :created, location: #survey_response }
else
format.html { render :new }
format.json { render json: #survey_response.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #survey_response.update(survey_response_params)
format.html { redirect_to #survey_response, notice: 'Survey response was successfully updated.' }
format.json { render :show, status: :ok, location: #survey_response }
else
format.html { render :edit }
format.json { render json: #survey_response.errors, status: :unprocessable_entity }
end
end
end
def destroy
#survey_response.destroy
respond_to do |format|
format.html { redirect_to survey_responses_url, notice: 'Survey response was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_survey_response
#survey_response = SurveyResponse.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def survey_response_params
params.permit(survey_response: [:answer, :survey_question_id, :user_id, :survey_answer_id])
end
end
Model
class SurveyResponse < ApplicationRecord
belongs_to :survey_question
belongs_to :user
end
You need to change your strong params, for array it looks like:
def survey_response_params
params.permit(survey_response: [:answer, :survey_question_id, :user_id, :survey_answer_id])
end
UPDATE:
I don't know anything about your models and controller, but I think it should be something like this in the controller
survey_response_params[:survey_response].each do |attrs|
SurveyResponse.new(attrs)
end
I'm having some issues with Overriding Named Route Parameters when I edit or create a post I get an error undefined method playerId for nil:NilClass. It still re-directs to the :id instead of the :playerId params only with create and edit methods.
Below, :playerId should be 101, but the 6 is the :id, not sure why it's picking it up.
SELECT `players`.* FROM `players` WHERE `players`.`playerId` = 6 LIMIT 1 [["playerId", "6"]]
Routes
resources :players, param: :playerId
Controller
def show
#player = Player.find_by(playerId: params[:playerId])
#season = PlayerStat.where("playerId = ?", #player.playerId).joins(:matches).where('matches.gameType = ?', 0).where('matches.teamId = ?', #player.teamId).group('year(matches.matchDate) DESC')
end
def edit
end
def create
#player = Player.new(player_params)
respond_to do |format|
if #player.save
format.html { redirect_to #player, notice: 'PLayer was successfully created.' }
format.json { render :show, status: :created, location: #player }
else
format.html { render :new }
format.json { render json: #player.errors, status: :unprocessable_entity }
end
end
end
def update
#player = Player.find params[:playerId]
respond_to do |format|
if #player.update(player_params)
format.html { redirect_to #player, notice: 'Player was successfully updated.' }
format.json { render :show, status: :ok, location: #player }
else
format.html { render :edit }
format.json { render json: #player.errors, status: :unprocessable_entity }
end
end
end
private
def set_player
#player = Player.find_by(playerId: params[:playerId])
end
def player_params
params.require(:player).permit(:playerId, :first_name, :last_name, :dob, :teamId, :jumper_no, :height, :weight, :image, team_attributes: [:teamId, :name], player_stats_attributes: [:playerId, :gameDate, :kicks, :marks])
end
undefined method playerId for nil:NilClass
The problem is params[:layerId] is nil upon a successful create or update because you aren't passing any playerId for the redirect_to. So #player is nil which resulted in that error. Changing your code to below should fix the error.
format.html { redirect_to player_path(#player.playerId), notice: 'PLayer was successfully created.' }
Same for update too.
you can define full routes like this:
get '/player/:playerId' => 'players#show'
get '/player/:playerId/edit' => 'players#edit'
I'm building a rails app where users can log on and see a table of their SAT test scores. Users "has_many" scores and Scores "belongs_to" users. Currently it is set up so that the user can post their own scores. What I want is for an admin to post the scores and the user will just see the table on their show page. The "admin" is just a boolean field in users that I set to true for the admins.
Here is the scores controller:
class ScoresController < ApplicationController
def index
#scores = Score.all
end
def show
#score = Score.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #score }
format.js
end
end
def new
#score = Score.new
end
def create
#score = current_user.scores.new(params[:score])
#user = current_user
respond_to do |format|
if #score.save
format.html { redirect_to #score.user, notice: 'Score was successfully created.' }
format.json { render json: #score, status: :created, location: #score }
else
format.html { render action: 'new' }
format.json { render json: #score.errors, status: :unprocessable_entity }
end
end
end
def update
#score = Score.find(params[:id])
respond_to do |format|
if #score.update(params[:score])
format.html { redirect_to #score.user, notice: 'Score was successfully updated.' }
format.json { render action: 'show', status: :ok, location: #score }
else
format.html { render action: 'edit' }
format.json { render json: #score.errors, status: :unprocessable_entity }
end
end
end
def edit
#score = Score.find(params[:id])
end
def destroy
#score = Score.find(params[:id])
if #score.present?
#score.destroy
end
redirect_to #score.user
end
end
I know I'd have to change the scores controller so that it didn't rely on current_user to create and edit scores. I'm just not sure how to implement that. Let me know if you need more info! Thanks.
First, you'll need to add a select tag in your view to select which user you want to post as:
- if current_user.is_admin?
= f.select :user_id, options_for_select(User.all.map{ |u| [u.username, u.id] })
- else
= f.hidden_field :user_id, value: current_user.id
Then, on the server-side, we will double-check that current_user is an admin to allow the creation of a Score for another User:
def create
#score = Score.new(params[:score])
if current_user.id != #score.user_id # Someone is trying to create a Score for someone else!
#score.errors.add(:user_id, "You shall not create Score for other users than you, you evil hacker!") unless current_user.is_admin?
end
respond_to do |format|
if #score.save
format.html { redirect_to #score.user, notice: 'Score was successfully created.' }
format.json { render json: #score, status: :created, location: #score }
else
format.html { render action: 'new' }
format.json { render json: #score.errors, status: :unprocessable_entity }
end
end
end
I omitted the part #user = current_user because usually current_user is a helper method than can be accessed directly in the views, so instead of using #user in the create view, use current_user instead.
I have an object called Job that belong to another object
called client in a many relationship.
Here's my job model
class Job < ActiveRecord::Base
belongs_to :client
end
Here's my Client model
class Client < ActiveRecord::Base
has_many :jobs
end
For a new job, I simply want to assign it during creation to a client.
When I try to create a new job however. All im seeing in my view is the id of the job instead of the name and the internals of the created model are also empty.
When I try to edit the job and save it again im recieving the following error.
Client(#2157214400) expected, got String(#2151988620)
Application Trace | Framework Trace | Full Trace
app/controllers/jobs_controller.rb:61:in `block in update'
app/controllers/jobs_controller.rb:60:in `update'
I guess this could be because my controller is wrong in some way but this is my first app so im not quite sure where to look.
Here's my controller.
class JobsController < ApplicationController
def index
#job = Job.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #job }
end
end
def show
#job = Job.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #job }
end
end
def new
#job = Job.new(params[:id])
respond_to do |format|
format.html # new.html.erb
format.json { render json: #job }
end
end
def edit
#job = Job.find(params[:id])
end
def create
#job = Job.new(params[:jobs])
respond_to do |format|
if #job.save
format.html { redirect_to #job, notice: 'job was successfully created.' }
format.json { render json: #job, status: :created, location: #job }
else
format.html { render action: "new" }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
def update
#job = Job.find(params[:id])
respond_to do |format|
if #job.update_attributes(params[:job])
format.html { redirect_to #job, notice: 'job was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #job.errors, status: :unprocessable_entity }
end
end
end
def destroy
#job = Job.find(params[:id])
#job.destroy
respond_to do |format|
format.html { redirect_to :jobs }
format.json { head :no_content }
end
end
end
Any pointers or a nod in the right direction would be appreciated.
The problem is because Activerecord expected an instance of Client object , and it has method client= (because belogs_to association)
When you bind AR object from request you should use client_id parameter instead of client
you can read about http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to
if client count is short you can use select with client_id as name
Example http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html
so you can do something like that
select("job", "client_id", Client.all.collect {|c| [ c.name, c.id ] }, {:include_blank => 'None'})
instead of
f.text_field :client, :class => 'text_field'