where all is devise's current_user method is available? Models? Controllers? Views? Helpers?
I have a Question model which belongs to User. So while saving new Question what is the best way to store user_id in Question?
QuestionsController as of now
def create
#question = Question.create(params[:question])
#question.save
render text: "Question created!"
end
From your code, and assuming that you have a has_many relationship, I would say that the best way to create a question for a user would be something like this:
#question = current_user.questions.create(params[:question])
Also, create is already calling save. If you want to manually call it you should use current_user.questions.build.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am new to rails and not able to figure out how these (new , index,show and create) method work.
eg .
class NameofController<ApplicationController
def new
end
def show
end
.
.
end
I am going to show you how this would work for a simple blog post application, because that was the best way for me to learn it when I started Rails. Simply put, here is how you normally use the following CRUD (Create, Read, Update, and Destroy) functions:
show: Use this to show a single post that has been created.
new: Use this to tell your program how to create a new post (I show you how to do this simply in the code at the bottom).
create: Use this to tell your program what to do once you are actually creating the post (new just initializes the process, while create actually does something with it).
index: Use this to show all posts that have been created. This is like the homepage for all of the posts.
Here is an example of what basic CRUD looks like (You didn't ask about the update and destroy methods, but I will include them in the code just for you to see how they all work together).
class PostsController < ApplicationController
def new
#post = Post.new
end
def index
#posts = Post.search(params[:search])
end
def create
#listing = Listing.new(listing_params)
#listing.user = current_user
if #listing.save
flash[:success] = "Your listing was successfully saved."
redirect_to listing_path(#listing)
else
render 'new'
end
end
def show
# Note sometimes you don't need to add anything other than declaring the method
end
def edit
# Note sometimes you don't need to add anything other than declaring the method
end
def update
if #post.update(post_params)
flash[:success] = "Your listing was successfully updated."
redirect_to listing_path(#listing)
else
render 'edit'
end
end
def destroy
#post.destroy
flash[:danger] = "Post was successfully deleted"
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title,:description)
end
end
I hope that this helps you.
Those seems to be four of the seven common resourceful actions.
Resource routing allows you to quickly declare all of the common
routes for a given resourceful controller. Instead of declaring
separate routes for your index, show, new, edit, create, update and
destroy actions, a resourceful route declares them in a single line of
code.
Browsers request pages from Rails by making a request for a URL using
a specific HTTP method, such as GET, POST, PATCH, PUT and DELETE. Each
method is a request to perform an operation on the resource. A
resource route maps a number of related requests to actions in a
single controller.
When your Rails application receives an incoming request for:
DELETE /photos/17
it asks the router to map it to a controller action. If the first
matching route is:
resources :photos
Rails would dispatch that request to the destroy action on the photos
controller with { id: '17' } in params.
In Rails, a resourceful route provides a mapping between HTTP verbs
and URLs to controller actions. By convention, each action also maps
to a specific CRUD operation in a database. A single entry in the
routing file, such as:
resources :photos
See Rails Routing from the Outside In.
I have a table questions(:id, :description) with model "question.rb" and a table answers(:id ,:question_id, :answer_descriptin) with model "answer.rb".
How can I show all questions and their answers in one page within a form partial like an questionnaire or an exam?
any idea?
You need to add a has_many association to the Question model:
has_many :answers
And then you can use fields_for to display sub forms for each answer within a question.
You might also want to look at Qwester
I'm adding a site-wide form for asking questions on a rails site. The models/views/controllers for the resource question are already created. Going to question/new shows the form as you'd expect. Now I want to display a site-wide question form (the only difference with this one is that it only shows mandatory fields). Question: should I create a new question object in application_controller and pass that to the rails form_for helper, or should I create a new _form2 partial(in the question view) and just include that in my site-wide template?
Thank you.
Create a question_form partial in the views/shared folder, and reference that from the site wide template.
Edit: in reply to where to get the #question variable from
You have two options in my mind, you can load the variable in ApplicationController:
class ApplicationController < ActionController::Base
before_filter :load_question
def load_question
#question = Question.new
end
...
end
(You should be careful of conflicts with the #question variable in this case)
Or probably better, you can create a method in ApplicationHelper:
module ApplicationHelper
def question_form
question = Question.new
raw render 'shared/question_form', :question => question
end
...
end
Then in your view, instead of referencing the partial, you reference the helper:
<%= question_form %>
In this case you would need to reference the variable in the partial as a local variable, so question instead of #question.
Hope that helps.
I'm not sure how to even research this question so maybe some awesome rails developer can point me in the right direction.
I have a model that's holding a question and correct answer. On the show view, I want the user to enter their answer into an input field and upon pressing submit, their answer is compared to the one held in the model. I don't need to save their answer.
Thoughts?
You could use a non ActiveRecord model for that. Something like this:
class UserAnswer # note that this class doesn't inherit from ActiveRecord::Base
attr_accessor :question_id, :answer
def initialize(params)
#question_id = params[:question_id]
#answer = params[:answer]
end
def correct?
q = QuestionAnswerModel.find(self.question_id)
q.answer == self.answer
end
end
Then in your controller you can do something like this:
user_answer = UserAnswer.new(params) # params contains :question_id and :answer
user_answer.correct? # returns true or false
A simple way is to save the answer confirmation only if it is equal to the answer.
Model:
question
answer
answer_confirmation
Then proceed to make the form as you normally would.
In the model add
validate :check_answer
def check_answer
errors.add(:answer, "Must be the same as answer confirmation") if answer!= answer_confirmation
end
I have a few questions relating to a Transaction object that I'm creating.
Transaction belongs_to Loan and Loan has_many Transactions.
Therefore, I setup a nested route:
resources :loans do
resources :transactions
end
My question is: How do I pass the loan value into the Transaction's 'loan_id' field? Is this best done in the controller or as a hidden_field in the form? Does the nested route create an easy way to grab this variable?
I assumed this would be done automatically, but the field is empty when I saved it as-is.
Any help would be greatly appreciated!
if you call a specific transaction, the route for a new transaction will be
loans/:loan_id/transactions/new
you could use model association like this: in your create action:
#transaction = Loan.find(params[:loan_id]).transactions.build
that way your new #transaction will be already populated with the loan_id
Consider adding a before_filter to your controller and having it call a private method to grab the :id across all actions. Place this at the top of your transactions controller:
before_filter :load_loan
And then after all the actions, add:
private
def load_loan
#loan.find(params[:loan_id])
end
Use it like this in your new action:
#transaction = #loan.transactions.build