this is the case:
models/product.rb
belongs_to :brand
models/brand.rb
has_many :products
controllers/products_controller.rb
class ProductsController < ApplicationController
def new
#product = Product.new
#brands = Brand.all
end
def create
#product = Product.new(params[:product])
if #product.save
redirect_to :show
else
render :new, format: :html
end
end
end
On product create the user can add a brand name and if the user add a brand name on next time to create a product the form for the brand did not show again.
Someone please have a idea how to do something like that on rails?
That's something to add in your view.
Use a condition around your brand form :
form #product do |f|
f.text_field :name
if not #product.new_record?
f.select_field :brand_id, #brands, :id
end
end
Related
I've spent a while trying to debug this behavior unsuccessfully, so I'm hoping for help figuring out why my nested resource parameters appear to be getting included in the URL in the wrong order. For some reason, adding and deleting lessons for a course works, but editing a lesson crashes because ActiveRecord tries to find a lesson using the course ID and vice versa.
Course and lesson models
class Course < ApplicationRecord
has_many :lessons, dependent: :destroy
extend FriendlyId
friendly_id :title, use: :slugged
class Lesson < ApplicationRecord
belongs_to :course
extend FriendlyId
friendly_id :title, use: :slugged
Lessons controller
class LessonsController < ApplicationController
before_action :set_lesson, only: [:show, :edit, :update, :destroy ]
def index
#lessons = Lesson.all
end
def show
end
def new
#lesson = Lesson.new
#course = Course.friendly.find(params[:course_id])
authorize #lesson
end
def edit
authorize #lesson
end
def create
#lesson = Lesson.new(lesson_params)
#course = Course.friendly.find(params[:course_id])
#lesson.course_id = #course.id
if #lesson.save
redirect_to course_lesson_path(#course, #lesson), notice: "Lesson was successfully created."
else
render :new, status: :unprocessable_entity
end
end
def update
authorize #lesson
if #lesson.update(lesson_params)
redirect_to course_lesson_path(#course, #lesson), notice: "Lesson was successfully updated."
else
render :edit
end
end
def destroy
authorize #lesson
#lesson.destroy
redirect_to course_path(#course), notice: "Lesson was successfully destroyed."
end
private
def set_lesson
#course = Course.friendly.find(params[:course_id])
#lesson = Lesson.friendly.find(params[:id])
end
def lesson_params
params.require(:lesson).permit(:title, :content, :course_id)
end
end
Routes
resources :courses do
resources :lessons
end
And what shows up when I do rails routes:
edit_course_lesson GET /courses/:course_id/lessons/:id/edit(.:format)
However, when I actually edit a lesson, the parameters seem to get switched, which causes a crash. See below for an example of where it thinks the fourth lesson is the course.
URL: /courses/fourth-lesson/lessons/forensic-science-344/edit
ActiveRecord::RecordNotFound in LessonsController#edit
can't find record with friendly id: "fourth-lesson"
private
def set_lesson
#course = Course.friendly.find(params[:course_id]) <- Crashes on this line
#lesson = Lesson.friendly.find(params[:id])
end
Update: here's the form for editing a lesson.
.container
= simple_form_for([#course, #lesson]) do |f|
= f.error_notification
= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present?
.form-inputs
= f.input :title
= f.input :content
%small
= f.error :content, class: 'text-danger'
.form-actions
= f.button :submit, class: 'btn btn-primary my-4'
It turns out that I didn't pass in the course parameter on the edit link. I had link_to 'Edit', edit_course_lesson_path(lesson).
It should have been edit_course_lesson_path(#course, lesson).
Thanks for everyone's patience, and many thanks to Deepesh for finally getting it into my head to look at the edit link.
I have two models Hotel and Address.
Relationships are:
class Hotel
belongs_to :user
has_one :address
accepts_nested_attributes_for :address
and
class Address
belongs_to :hotel
And I need to save in hotels table and in addresses table from one form.
The input form is simple:
<%= form_for(#hotel) do |f| %>
<%= f.text_field :title %>
......other hotel fields......
<%= f.fields_for :address do |o| %>
<%= o.text_field :country %>
......other address fields......
<% end %>
<% end %>
Hotels controller:
class HotelsController < ApplicationController
def new
#hotel = Hotel.new
end
def create
#hotel = current_user.hotels.build(hotel_params)
address = #hotel.address.build
if #hotel.save
flash[:success] = "Hotel created!"
redirect_to #hotel
else
render 'new'
end
end
But this code doesn't work.
ADD 1
Hotel_params:
private
def hotel_params
params.require(:hotel).permit(:title, :stars, :room, :price)
end
ADD 2
The main problem is I don't know how to render form properly. This ^^^ form doesn't even include adress fields (country, city etc.). But if in the line
<%= f.fields_for :address do |o| %>
I change :address to :hotel, I get address fields in the form, but of course nothing saves in :address table in this case. I don't understand the principle of saving in 2 tables from 1 form, I'm VERY sorry, I'm new to Rails...
You are using wrong method for appending your child with the parent.And also it is has_one relation,so you should use build_model not model.build.Your new and create methods should be like this
class HotelsController < ApplicationController
def new
#hotel = Hotel.new
#hotel.build_address #here
end
def create
#hotel = current_user.hotels.build(hotel_params)
if #hotel.save
flash[:success] = "Hotel created!"
redirect_to #hotel
else
render 'new'
end
end
Update
Your hotel_params method should look like this
def hotel_params
params.require(:hotel).permit(:title, :stars, :room, :price,address_attributes: [:country,:state,:city,:street])
end
You should not build address again
class HotelsController < ApplicationController
def new
#hotel = Hotel.new
end
def create
#hotel = current_user.hotels.build(hotel_params)
# address = #hotel.address.build
# the previous line should not be used
if #hotel.save
flash[:success] = "Hotel created!"
redirect_to #hotel
else
render 'new'
end
end
Bottom line here is you need to use the f.fields_for method correctly.
--
Controller
There are several things you need to do to get the method to work. Firstly, you need to build the associated object, then you need to be able to pass the data in the right way to your model:
#app/models/hotel.rb
Class Hotel < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end
#app/controllers/hotels_controller.rb
Class HotelsController < ApplicationController
def new
#hotel = Hotel.new
#hotel.build_address #-> build_singular for singular assoc. plural.build for plural
end
def create
#hotel = Hotel.new(hotel_params)
#hotel.save
end
private
def hotel_params
params.require(:hotel).permit(:title, :stars, :room, :price, address_attributes: [:each, :address, :attribute])
end
end
This should work for you.
--
Form
Some tips for your form - if you're loading the form & not seeing the f.fields_for block showing, it basically means you've not set your ActiveRecord Model correctly (in the new action)
What I've written above (which is very similar to that written by Pavan) should get it working for you
Basically I want it so that on my views when you sign in you are only able to view the projects and assets associated with that project if you are the one who created them. Here is my current controller:
class ProjectsController < ApplicationController
before_filter :authenticate_user!
def show
#project = Project.find(params[:id])
end
def new
#project = Project.new
end
def create
#project = Project.new(project_params)
#project.user_id = current_user.id if current_user
if #project.save
flash[:notice] = "Name successfully added."
redirect_to(#project, :action => 'show')
else
render(:action => 'new')
end
end
private
def project_params
params.require(:project).permit(:name, :id, :user_id)
end
end
Also as my user has_many projects and projects has_many assets and projects has a user_id column and index, does that mean that a created asset is automatically associated with that user or do I need to add a user_id to assets as well.
The reason I say this is because I want to be able to in my view:
#views/projects/show.html.erb
<% current_user.assets.each do |f| %>
<%= f.name %>
<%= f.url %>
<% end %>
or something like that.
Also if on that same page I wanted to add a create new asset button would I need to create an asset controller with a create action or could I just have it in the projects controller.
What you want to do is scope Project through current_user, like so:
class ProjectsController < ApplicationController
before_filter :authenticate_user!
def show
#project = current_user.projects.find(params[:id])
end
def new
#project = current_user.projects.build
end
def create
#project = current_user.projects.build(project_params)
if #project.save
flash[:notice] = "Name successfully added."
redirect_to(#project, :action => 'show')
else
render(:action => 'new')
end
end
private
def project_params
# removed :user_id for security reasons (see below)
params.require(:project).permit(:name, :id)
end
end
Also as my user has_many projects and projects has_many assets and
projects has a user_id column and index, does that mean that a created
asset is automatically associated with that user or do I need to add a
user_id to assets as well.
To do this, map the relation using has_many through: --
class User
has_many :projects
has_many :assets, through: :projects
end
Also, if I wanted to create a new asset in the projects/show.html.erb
view, would I just create an assets controller with a new method and
then route the button to that method? or could I do this inside the
projects controller?
For this, you would use accepts_nested_attributes_for in your Profile model:
class Profile
accepts_nested_attributes_for :assets
end
Then update your permitted project_params:
def project_params
params.require(:project).permit(:name, :id, assets_attributes: [:etc])
end
Couple of notes. Update assets_attributes: [:etc] with Asset attributes that should be accessible. That might be :name, :file, etc. Second, notice I've removed :user_id. This is a very important concept. Permitting :user_id means the form can be injected with that attribute. In this case, it would allow users to assign the created Project to any user they like.
#post.comments.all is clear. and i dont see any errors after i send form. When i click "Submit" i sent to posts/id/comments, but
my routes.rb
resources :posts do
resources :comments
end
post controller
def show
#current_user ||= User.find(session[:user_id]) if session[:user_id]
#commenter = #current_user
#post = Post.find(params[:id])
#comment = Comment.build_from( #post, #commenter.id, "234234" )
#comments = Comment.all
respond_to do |format|
format.html
format.json { render json: #post }
end
end
comments controller
class CommentsController < ApplicationController
def index
#comments = #post.comments.all
end
def create
#post = Post.find(params[:post_id])
#comment = #post.comments.new params[:comment]
if #comment.save
redirect_to #post # comment not save, so i dont redirect to this page
else
# is that there
end
end
end
post model
acts_as_commentable
has_many :comments
comment model
class Comment < ActiveRecord::Base
acts_as_nested_set :scope => [:commentable_id, :commentable_type]
attr_accessible :commentable, :body, :user_id
validates :body, :presence => true
validates :user, :presence => true
# NOTE: install the acts_as_votable plugin if you
# want user to vote on the quality of comments.
#acts_as_votable
belongs_to :commentable, :polymorphic => true
# NOTE: Comments belong to a user
belongs_to :user
# Helper class method that allows you to build a comment
# by passing a commentable object, a user_id, and comment text
# example in readme
def self.build_from(obj, user_id, comment)
new \
:commentable => obj,
:body => comment,
:user_id => user_id
end
#helper method to check if a comment has children
def has_children?
self.children.any?
end
# Helper class method to lookup all comments assigned
# to all commentable types for a given user.
scope :find_comments_by_user, lambda { |user|
where(:user_id => user.id).order('created_at DESC')
}
# Helper class method to look up all comments for
# commentable class name and commentable id.
scope :find_comments_for_commentable, lambda { |commentable_str, commentable_id|
where(:commentable_type => commentable_str.to_s, :commentable_id => commentable_id).order('created_at DESC')
}
# Helper class method to look up a commentable object
# given the commentable class name and id
def self.find_commentable(commentable_str, commentable_id)
commentable_str.constantize.find(commentable_id)
end
end
post view
%h2 Add a comment:
- #comments.each do |c|
= #c.body
= form_for([#post, #comment]) do |f|
.field
= f.label :body
%br/
= f.text_area :body
.actions
= f.submit
Thanks in advance and sorry for bad english
First of all you can debug why #comment.save return false yourself - just add p #comment.errors in else block and check server log.
It seems for me that you try to save invalid comments because you don't have setup user for #comment in action CommentsController#create. Comment validates presence of user!
There are several ways how to fix it. Analyzing your code I think the simplest way for you is modify CommentsController#create
#CommentsController
def create
#current_user ||= User.find(session[:user_id]) if session[:user_id]
#post = Post.find(params[:post_id])
#comment = #post.comments.new params[:comment]
#comment.user = #current_user
if #comment.save
redirect_to #post # comment not save, so i dont redirect to this page
else
# is that there
end
end
Another way is to use some gem for authentication - I recommend devise
One more way (very bad way) is to pass user_id through hidden field (you have defined #current_user in PostsController#show and user_id in attr_accessible list in Comment). But this is easy way to hack your application and write comments on behalf of any user in system!
I have three models: Lesson, Situation, Fate(join table).
In this app, A situation can have many lessons and a lesson can belong to multiple situations.
I would essentially like the tables to look like this.
Situation
id.....name.....................description
1.....Ordering Food......You go into a restaurant and order food.
2.....Introduce yourself.You meet someone for the first time and you introduce yourself.
Lesson
id.....name............description..............lesson_text
1......Order food....How to order food..Blah blah blah, this is how you order food.
2......Call the waiter.How to call the waiter Blah blah blah, this is how you call the waiter
3 Pay for food How to pay for food Blah blah blah, this is how you pay for food.
4 Greet a person How to greet a person Blah blah blah, this is how you greet a person.
5 Ask a question How to ask a question Blah blah blah, this is how you ask a question.
Fate
situation_id lesson_id required
1.................1...............yes
1.................2...............yes
1.................3...............no
2.................3...............yes
2.................4...............yes
2.................5...............yes
I have the tables set up but I'm not sure how I would associate a lesson to a situation.
This is what my application looks like currently
Situations controller
class SituationsController < ApplicationController
def index
#situations = Situation.all
end
def new
#situation = Situation.new
end
def create
#situation = Situation.new(params[:situation])
respond_to do |format|
if #situation.save
format.html { redirect_to #situation }
end
end
end
def show
#situation = Situation.find(params[:id])
#lesson = #situation.lessons.new
end
def edit
#situation = Situation.find(params[:id])
end
def update
#situation = Situation.find(params[:id])
respond_to do |format|
if #situation.update_attributes(params[:situation])
format.html { redirect_to #situation }
end
end
end
def destroy
#situation = Situation.find(params[:id])
#situation.destroy
respond_to do |format|
format.html { redirect_to situations_path }
end
end
end
Lessons controller
class LessonsController < ApplicationController
def index
#lessons = Lesson.all
end
def new
#lesson = Lesson.new
end
def create
#lesson = Lesson.new(params[:lesson])
respond_to do |format|
if #lesson.save
format.html { redirect_to #lesson }
end
end
end
def show
#lesson = Lesson.find(params[:id])
end
def edit
#lesson = Lesson.find(params[:id])
end
def update
#lesson = Lesson.find(params[:id])
respond_to do |format|
if #lesson.update_attributes(params[:lesson])
format.html { redirect_to #lesson }
end
end
end
def destroy
#lesson = Lesson.find(params[:id])
#lesson.destroy
respond_to do |format|
format.html { redirect_to lessons_path }
end
end
end
Routes
root :to => 'situations#index'
resources :situations do
resources :lessons
end
resources :difficulties
Situation.rb
class Situation < ActiveRecord::Base
attr_accessible :name, :description
has_many :fates
has_many :lessons, :through => :fates
end
Lesson.rb
class Lesson < ActiveRecord::Base
attr_accessible :name, :description, :difficulty_id, :lesson_text
has_many :fates
has_many :situations, :through => :fates
end
Fate.rb
class Fate < ActiveRecord::Base
belongs_to :lesson
belongs_to :situation
end
Thanks for the help! and I'm really sorry about the messy formatting.
So if you are creating a new situation and want to also create new lessons that will be associated with it..
app/models/situation.rb
attr_accessible :name, :description, :difficulty_id, :lesson_text, :lessons_attributes
accepts_nested_attributes_for :lessons
app/controllers/situations_controller.rb
def new
#situation = Situation.new
2.times do{#situation.lessons.build}
respond_to do |format|
format.html
end
end
app/views/lessons/_form.html.erb
<% form_for #situation do |f| %>
<%= f.text_field :name %>
<%= f.text_field :description %>
<% f.fields_for :situations do |lesson_field| %>
<%= lesson_field.text_field :name %>
<%= lesson_field.text_field :lesson_text %>
<% end %>
<%= f.submit %>
<% end %>
Essentially you need a nested form (there is plenty examples). I typed this off the iPhone, hope it works )