Nested Route New object creation does not complete if loop - ruby-on-rails

I currently have review model that will allow a user to create reviews for a tea model. The user who creates the review can edit or delete the review. I have a nested route within teas that allows you to create a new review for teas as you are viewing all reviews for that specific tea. Currently the nested new route does not allow creation as well as a google authenticated user can not create a review. Below is my controller action and view. I am not experiencing any error it just appears to rollback the database and follow the else logic and render the new page again.
Model
class Review < ApplicationRecord
belongs_to :user
belongs_to :tea
validates :title, presence: true
validates :rating, numericality: {only_integer: true, greater_than_or_equal_to: 0, less_than: 11}
validates :tea, uniqueness: {scope: :user, message: "has already been reviewed by you" }
scope :order_by_rating, ->{left_joins(:reviews).group(:id).order('avg(rating) desc')}
end
Controller Action
def create
#review = current_user.reviews.build(review_params)
if #review.valid?
#review.save
redirect_to new_review_path(#review)
else
render :new
end
end
View
<%= form_for Review.new do |f|%>
<% if params[:tea_id] %>
<%= f.hidden_field :tea_id %>
<% else %>
<div>
<%= f.label :tea_id, "Select a Tea Blend" %>
<%= f.collection_select :tea_id, Tea.alpha, :id, :flavor_and_brand, include_blank: true %>
</div>
<% end %>
<div>
<%= f.label :rating %>
<%= f.number_field :rating, min:0, max:10 %>
</div>
<br>
<div>
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<br>
<div>
<%= f.label :content %>
<br>
<%= f.text_area :content, size: "60x25" %>
</div>
<br>
<%= f.submit %>
<% end %>

The simple answer was that I did not include create in my before action. This is what was causing my set_tea to not be automatically done as a before action.

The correct way to do this is by defining a nested route and setting up the form so that it posts to that route. So instead of creating a single form where the user has to select the tea you create a form on the show page or by each tea in a index page where the user can create reviews.
# config/routes.rb
resources :teas do
resources :reviews, shallow: true
end
shallow: true makes it so that the member actions (show, edit, update, destroy) are not nested.
Then setup a partial for the form so that you can reuse it:
# app/views/reviews/_form.html.erb
<%= form_for([local_assigns(:tea), review]) do |f| %>
<div class="field">
<%= f.label :rating %>
<%= f.number_field :rating, min:0, max:10 %>
</div>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :content %>
<%= f.text_area :content, size: "60x25" %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
By passing an array you get the nested route as the action attribute (/teas/1/reviews) and don't have to monkey around with a hidden input. local_assigns(:tea) avoids a NoMethodError if its not passed to the partial. The array is compacted so that this partial will work for both creating and updating.
# app/views/reviews/new.html.erb
<%= render partial: 'form', tea: #tea, review: #review >
# app/views/reviews/edit.html.erb
<%= render partial: 'form', review: #review >
# app/views/teas/show.html.erb
<h2>Review this tea</h2>
<%= render partial: 'reviews/form', tea: #tea, review: #tea.reviews.new >
In the controller you can just fetch the tea from params[:tea_id] since you passed it in the path.
class ReviewsController < ApplicationController
before_action :set_tea, only: [:new, :index, :create]
before_action :set_review, only: [:show, :edit, :update, :destroy]
# POST /teas/1/reviews
def create
# creating the review off the tea reveals intent better than doing
# it off the user
#review = #tea.reviews.new(review_params) do |r|
r.user = current_user
end
# Always check if the record is actually persisted
# - not just if the applications validations pass!
if #review.save
# you could also redirect to the review but this makes more
# sense from a ux perspective
redirect_to #tea, notice: 'Thank you for your review'
else
render :new
end
end
# GET /reviews/:id/edit
def edit
end
# PUT|PATCH /reviews/:id
def update
if #review.update(review_params)
redirect_to #review, notice: 'Review updated.'
else
render :edit
end
end
private
def set_tea
#tea = Tea.find(params[:tea_id])
end
def set_review
#review = Review.find(params[:id])
end
def review_params
params.require(:review).permit(:rating, :title)
end
end

Related

has_many join form with collection checkboxes not saving more than one checkbox value

I am working on a form for a editorial calendar app. I have two things going out that are pretty similar and not working.
Working with 3 models: Platforms, Posts and Calendars. They are join tables. Platform <=> Post, Post <=> Calendars
Post/new & Post/edit form:
<div class="container">
<div class="form-field">
<%= form_for #post do |f| %>
<%= f.label :title %>
<%= f.text_field :title, required: true %> <br>
Title is required.
</div>
<div class="form-field">
<%= f.label :content%>
<%= f.text_area :content%>
</div>
<div class="form-field">
<%= f.label :link %>
<%= f.text_field :link %>
</div>
<div class="file-field">
<%= f.label :picture%>
<%= f.file_field :picture, id: :post_picture%>
</div>
<div class="file-field">
<%= f.label :finalized %>
<%= f.radio_button :finalized , true%>
<%= f.label :finalized, "Yes" %>
<%= f.radio_button :finalized, false %>
<%= f.label :finalized, "No" %>
</div>
<%= f.hidden_field :user_id %> <br>
<div class="form-field">
<%= f.fields_for :platform_attributes do |platform| %>
<%= platform.label :platform, "Social Platforms"%>
<%= platform.collection_check_boxes :platform_ids, Platform.all, :id, :name %> <br> <br>
</div>
<div>
<h4> Or Create a new platform: </h4>
<%= platform.label :platform, 'New Platform'%>
<%= platform.text_field :name%> <br> <br>
</div>
<% end %>
<%= f.submit%>
<% end %>
</div>
My post controller is handling the checkboxes issue, and the "schedule post" issue. It will only allow me to schedule for one calendar, and it does not save the updates and add additional calendars.
Posts Controller:
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :schedule_post, :destroy]
def new
#posts = current_user.posts.select {|p| p.persisted?}
#post = current_user.posts.build
#platforms = Platform.all
end
def edit
#calendars = current_user.calendars
#platforms = Platform.all
end
def create
#post = current_user.posts.build(post_params)
if #post.save
redirect_to post_path(#post)
else
redirect_to new_post_path
end
end
def update
#post.update(post_params)
if #post.save
redirect_to post_path(#post), notice: 'Your post has been updated.'
else
redirect_to edit_post_path(#post)
end
end
def schedule_post
#calendar_post = CalendarPost.new(calendar_post_params)
if #calendar_post.save
binding.pry
redirect_to post_path(#post)
else
render 'show'
end
end
private
def set_post
#post = Post.find(params[:id])
end
def set_calendars
#calendars = current_user.calendars
end
def post_params
params.require(:post).permit(:title, :content, :link, :finalized, :picture, :user_id, :platform_attributes => [:platform_ids, :name])
end
def calendar_post_params
params.require(:calendar_post).permit(:post_id, :calendar_id, :date, :time)
end
end
I want the user to be able to add a post to multiple platforms and multiple calendars because of the versatility of what someone may need.
I also have my setter in my Post model.
class Post < ApplicationRecord
has_many :calendar_posts
has_many :calendars, through: :calendar_posts
has_many :platform_posts
has_many :platforms, through: :platform_posts
belongs_to :user
def platform_attributes=(platform_attributes)
if platform_attributes['platform_ids']
platform_attributes.platform_ids.each do |id|
platform = Platform.find(id: id)
self.platforms << platform
end
end
if platform_attributes['name'] != ""
platform = Platform.find_or_create_by(name: platform_attributes['name'])
self.platforms << platform
end
end
thoughts? why are they not saving to more than one calendar or more than one platform if they choose to have more than one?
Here is the updated code... and more of what I know about these changes and what is happening.
My submit button is not working for some odd reason on my form, so I'm trying to get the params submitted but it won't even route to give me params even if I raise them, nothing is happening.
On the form you can choose checkboxes or add in a platform. If you add in a platform it creates that one but it does not also save the other ones you selected. If you go to edit the post, and click submit with changes, no page loads at all and nothing is happening in log. It's just idle.
<%= f.fields_for :platform_attributes do |platform| %>
assumes you are creating one platform... it says "these are the fields for this platform"
but platform_ids is intended to be a selection of a set of platforms... and probably should be outside of the fields_for section (which should only surround the name field).
try something like the following:
<div class="form-field">
<%= f.label :platform_ids, "Social Platforms"%>
<%= f.collection_check_boxes :platform_ids, Platform.all, :id, :name %> <br> <br>
</div>
<div>
<%= f.fields_for :platform_attributes do |platform| %>
<h4> Or Create a new platform: </h4>
<%= platform.label :name, 'New Platform'%>
<%= platform.text_field :name%> <br> <br>
<% end %>
<%# end fields_for %>
</div>
Also you'll need to update permit/require appropriately eg
def post_params
params.require(:post).permit(:title, :content, :link, :finalized, :picture, :user_id, :platform_ids, :platform_attributes => [:name])
end
Note: not tested - bugs are left as an exercise for the reader ;)

Rails passing params to different model and then saving it not working

I have a 'post' controller in that I have two variable title and body which I am passing through strong parameters.But I need to use two other variable which are path and name which are in different model name 'Document'..And also I am saving the content in database ..but unable to do so..getting this error view [posts/_form.html.erb]
undefined method `name' for #
[posts_controller]
class PostsController < ApplicationController
before_action :authenticate_user!
def index
#posts = Post.user_post(current_user).order('created_at DESC').paginate(:page => params[:page], :per_page => 5)
end
def new
#post = Post.new
end
def show
#post = find_params
end
def create
#post = Post.create(post_params)
#post.user = current_user
if #post.save
redirect_to #post
else
render 'new'
end
end
def edit
#post = find_params
end
def update
#post = find_params
if #post.update(post_params)
redirect_to #post
else
render 'edit'
end
end
def destroy
#post = find_params
#post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body)
Document.new(params,:files=>[])
end
def find_params
Post.find(params[:id])
end
end
[post/_form.html.erb]
<%= form_for #post,html: { multipart: true } do |f| %>
<% if #post.errors.any? %>
<div id="errors">
<h2><%= pluralize(#post.errors.count, "error") %> prevented this post from saving:</h2>
<ul>
<% #post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_field :body %><br>
<br>
<%= f.label :name %> <br>
<%= f.text_field :name %><br>
<br>
<br>
<%= f.label :path %><br>
<%= f.file_field :path %><br>
<%= f.submit %>
<% end %>
[document.rb]
class Document < ActiveRecord::Base
validates :name, presence: true
validates :path, presence: true
validates :resource_type, presence: true
validates :resource_id, presence: true
mount_uploader :path, PathUploader
validates :name, presence: true
# def self.abc
# params.permit(:name,:path)
# end
def initialize(params,file)
params=file[:name]
#params.permit(name =>:name,path =>:path)
end
end
undefined method `name' for #
You're referencing a non-existent attributes for your Post form:
<%= form_for #post,html: { multipart: true } do |f| %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_field :body %><br>
<%= f.submit %>
<% end %>
Remove :name & :path references.
--
If you want to pass "extra" attributes to another model, you need to use accepts_nested_attributes_for or set the params separately to your "primary" model:
#app/models/post.rb
class Post < ActiveRecord::Base
has_many :documents
accepts_nested_attributes_for :documents
end
#app/models/document.rb
class Document < ActiveRecord::Base
belongs_to :post
end
This will allow you to pass the documents as "nested" attributes of your Post model:
#app/controllers/posts_controller.rb
class PostsController < ApplicationController
def new
#post = Post.new
#post.documents.build
end
def create
#post = Post.new post_params
#post.save
end
private
def post_params
params.require(:post).permit(:title, :body, documents_attributes: [:name, :path])
end
end
#app/views/posts/_form.html.erb
<%= form_for #post do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body %>
<%= f.fields_for :documents do |d| %>
<%= d.text_field :name %>
<%= d.text_field :path %>
<% end %>
<%= f.submit %>
<% end %>
So undefined method on a model will indicate that, well, the method doesn't exist on the model. Want to see a model's methods? Post.methods. However, in this example, the column name is not defined on the model., and you're trying to tell Post that it has a name. What you need to do is nest your parameters.
While there is a ton of cleaning up that might want to focus on first, your answer is found in the accepts_nestable_attributes_for class methods, as shown here, http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html, and strong_params documentation as shown here, http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html
In your case, you want to create a new document from a post. Your permitted params hash will look like this,
params.require(:post).permit(:title, :body, :document_attributes => [:name])
Ensure that document_attributes is singular; if a person has_many pets (for example), then you'd have pets_attributes.
In your form, something that often trips people up is the builder.
<%= form_for #post do |f| %>
<%= f.text_field :title %>
<%= f.text_field :body %>
<%= f.fields_for #post.document do |document_field| %>
<%= document_field.text_field :name %>
<% end %>
<%= f.submit %>
<% end %>
Make sure that you're telling ERB that <%= f.fields_for %>, not just <% f.fields_for %>.

Can't render checkboxes in a Rails 4 many_to_many association?

I have a many_to_many association between Articles and Categories, using has_and_belongs_to_many in a Rails 4 app:
Here are the corresponding migration and classes:
class CategoriesArticles < ActiveRecord::Migration
def change
create_table :articles_categories, id: false do |t|
t.belongs_to :category, index: true
t.belongs_to :article, index: true
end
add_index :articles_categories, [:category_id, :article_id]
end
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :articles
end
class Article < ActiveRecord::Base
has_and_belongs_to_many :categories
end
When a user creates a new article, I simply want to give him or her the option to select categories that he/she wants to associate with the new article. I want the user to be able to select these categories with checkboxes.
Here's the ArticlesController:
class ArticlesController < ApplicationController
before_action :set_article, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, only: [:new, :create, :edit, :destroy, :update]
before_action :verify_own_article, only: [:destroy]
respond_to :html
...
def new
#categories = Category.all
#article = Article.new
respond_with(#article)
end
def create
# Creates article object with current_user_id, initial_comment, and URL
#article = current_user.articles.build(article_params)
# Uses Pismo (gem) to grab title, content, photo of URL
#article.populate_url_fields
if #article.save
flash[:success] = "Article created!"
# Might need to change the location of this redirect
redirect_to root_url
else
flash[:notice] = "Invalid article."
redirect_to new_article_path
end
end
def update
#article.update(article_params)
flash[:notice] = "Article successfully updated."
respond_with(#article)
end
private
def set_article
#article = Article.find(params[:id])
end
def article_params
params.require(:article).permit(:url, :title, :datetime, :content, :photo, :initial_comment)
end
# Ensure that a signed in user can only delete articles that they have posted
def verify_own_article
#article = current_user.articles.find_by_id(params[:id])
end
end
Here's the article new.html.erb view:
<h1>New article</h1>
<%= render 'form' %>
<%= link_to 'Back', articles_path %>
... and the form partial:
<%= form_for(#article) do |f| %>
<% if #article.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#article.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% #article.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :url %><br>
<%= f.text_field :url %>
</div>
<div class="field">
<%= f.label :initial_comment %><br>
<%= f.text_field :initial_comment %>
</div>
<% #categories.each do |t| %>
<div class="field">
<%= f.label t.name %>
<%= f.check_box "categories[#{t.id}]" %>
<br />
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
However, this is erroring for me, specifically the lines:
<% #categories.each do |t| %>
<div class="field">
<%= f.label t.name %>
<%= f.check_box "categories[#{t.id}]" %>
<br />
</div>
<% end %>
Specifically, it's telling me:
undefined method 'categories[1]' for #<Article:0x007f401193d520> when I try to render the New Article page. How do I fix this? Thanks.
It is better to use Rails collection_check_boxes helper instead of trying to create those checkboxes by hand. This helper already creates all the parameter / markup stuff you need in order to add or exclude items of a HABTM relation, all under the hood. So you might change you view to include the following:
<%= f.collection_check_boxes :categories_ids, #categories, :id, :name %>
Don't forget to add this in your strong parameters declaration (since you'll have to receive the selected categories ids and bind them to your Article model):
params.require(:article).permit(
:url, :title, :datetime, :content,
:photo, :initial_comment, categories_ids: []
)
For further customizations (html styling or structure for each checkbox), please refer to the complete documentation
I hope it helps :)

Rails 4 Nested form with devise logs me out on update

I have a nested form with the parent model built with devise and the child model without devise. I'm working on the edit form which has the user model fields and nested inside them expert model fields. The update/save works but logs me out and gives me an error saying "You need to sign in or sign up before continuing"
When I sign back in I see that the fields have been updated correctly. I would like it to not sign me out and show me the updated Edit page upon submitting the form.
User model - built with devise.
class User < ActiveRecord::Base
// some stuff
has_one :expert
accepts_nested_attributes_for :expert, :update_only => true
// more stuff
Expert model - built withOUT devise.
class Expert < ActiveRecord::Base
belongs_to :user
User controller:
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :only => [:show, :edit]
def edit
#user = User.friendly.find(params[:id])
#title = "Edit Profile"
end
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.friendly.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:id, :name, :email, :phone, :password, :role, :expert_attributes => [:id, :Location])
end
end
Expert controller:
def edit
#expert = Expert.find(params[:id])
#title = "Edit Expert Profile"
end
Edit user view form partial:
<%= form_for(#user) do |f| %>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :Name %><br>
<%= f.text_field :name, :class => "form-control" %>
</div>
<div class="field">
<%= f.label :Email %><br>
<%= f.text_field :email, :class => "form-control" %>
</div>
<div class="field">
<%= f.label :Phone %><br>
<%= f.text_field :phone, :class => "form-control" %>
</div>
<div class="field">
<%= f.label :Password %><br>
<%= f.text_field :password, :class => "form-control" %>
</div>
<div class="field">
<%= f.fields_for :expert do |e| %>
<%= e.label :Location %><br />
<%= e.text_field :Location %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
In your UsersController, you should add :update to the authenticate_user! filter:
before_filter :authenticate_user!, :only => [:show, :edit, :update]

RoR wrong number of arguments (0 for 1) form

Hi I'm trying to create a form, that at the same time, creates a list and associates products to it.
The problem is that the form keeps raising
wrong number of arguments (0 for 1)
Extracted source (around line #10):
7: <%= f.text_area :description, placeholder:
8: "Compose a description for it ..." %>
9: </div>
10: <%= l.fields_for :products do |builder| %>
11: <%= render 'shared/product_form', :l => builder %>
12: <% end %>
13: <%= l.submit "Create", class: "btn btn-large btn-primary" %>
App Trace is
app/views/shared/_list_form.html.erb:10:in `block in _app_views_shared__list_form_html_erb__184644094_33330696'
app/views/shared/_list_form.html.erb:1:in `_app_views_shared__list_form_html_erb__184644094_33330696'
app/views/lists/new.html.erb:7:in `_app_views_lists_new_html_erb__973495114_33282228'
The code is as follows:
---view----
--list_form--
<%= form_for(#list) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_field :name, placeholder:
"Come up with a name for your list" %>
<%= f.text_area :description, placeholder:
"Compose a description for it ..." %>
</div>
<%= f.fields_for :products do |builder| %>
<%= render 'shared/product_form', :f => builder %>
<% end %>
<%= f.submit "Create", class: "btn btn-large btn-primary" %>
<% end %>
--product_form--
<%= f.text_field :name, "Name:" %>
<%= f.text_area :description, :rows => 3 %>
---model---
--list--
class List < ActiveRecord::Base
attr_accessible :description, :name
belongs_to :user
has_many :products, :dependent => :destroy
accepts_nested_attributes_for :products, :reject_if => lambda { |a| a[:name].blank? }, :allow_destroy => true
has_many :list_categorization
has_many :category, :through => :list_categorization
validates :user_id, presence: true
validates :name, presence: true, length: {maximum: 10}
validates :description, length: {maximum: 140}
default_scope order: 'lists.created_at DESC'
def categorize!(category_id)
list_categorization.create!(category_id: category_id)
end
end
--product--
class Product < ActiveRecord::Base
attr_accessible :description, :donated, :name
validates :list_id, presence: true
belongs_to :list
end
---controllers---
--list_controller--
def new
#list = List.new
#products = #list.products.build
end
def create
#list = current_user.lists.build(params[:list]) if signed_in?
if #list.save
flash[:success] ="List " + #list.name + "created!"
render 'new'
end
--product_controller--
def new
#product = Product.new
end
def create
#product = #product.build(params[:product]) if signed_in?
if #product.save
flash[:success] ="Product " + #product.name + "created!"
end
You were right, I actually realized it after posting this, but now while trying to submit the form this happens:
The form contains 1 error.
* Name can't be blank
event tough I filled it correctly, this is what is getting passed
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
utf8: ✓
authenticity_token: 38CXjVORlj2RBgoTetIMoHomcVgOIlBU5rW3NTgkRkU=
list: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
name: list
description: this is a list
products_attributes: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
'0': !ruby/hash:ActiveSupport::HashWithIndifferentAccess
name: p1
description: this is a product
commit: Create
action: create
controller: lists
Where did that l come from? I'm pretty sure you need to change it to f:
<%= form_for(#list) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_field :name, placeholder: "Come up with a name for your list" %>
<%= f.text_area :description, placeholder: "Compose a description for it ..." %>
</div>
<%= f.fields_for :products do |builder| %>
<%= render 'shared/product_form', :l => builder %>
<% end %>
<%= f.submit "Create", class: "btn btn-large btn-primary" %>
<% end %>
Update
There are a few problems with your code. First of all when you call #list = current_user.lists.build(params[:list]) if signed_in? it means that if there is no user signed in that object won't be created at all. The proper way to do something like this would be with a before_filter in your controller.
Secondly #product = #product.build(params[:product]) won't work. You haven't initialized a Product object yet, and you haven't assigned it to #product yet. Also build is used for associations. You need to change this to #product = Product.new(params[:product]).
Lists controller:
before_filter :user_signed_in? # add to products controller as well
# if you need this filter only on certain actions then do:
# before_filter :user_signed_in?, only: [:new, :create]
def new
#list = current_user.lists.build
#products = #list.products.build
end
def create
#list = current_user.lists.build(params[:list])
if #list.save
flash[:success] = "List " + #list.name + " created!"
redirect_to lists_path # this part was missing!
else # this was also missing
render 'new'
end # you had an 'if' with no 'end'
end
private
# add the following to Products controller as well, or if you
# use it a lot then place it in your application controller
def user_signed_in?
unless signed_in?
flash[:notice] = "You must first sign in"
redirect_to sign_in_path
end
end
Products controller:
def new
#product = Product.new
end
def create
#product = Product.new(params[:product]
if #product.save
flash[:success] = "Product " + #product.name + " created!"
redirect_to #product
else
render 'new'
end
end
As far as I remember however, the products#create action won't be used when saving a product through a nested form, the lists#create action will be used for both.
To learn more about nested forms have a look at these railscasts.
Once you've updated your code and gone through those videos, if you're still getting errors I would recommend to create a new question since this one is getting long and messy already :)
you forgot to do this:
rails generate migration add_remember_token_to_users

Resources