RoR wrong number of arguments (0 for 1) form - ruby-on-rails

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

Related

Nested Route New object creation does not complete if loop

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

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 %>.

accepts_nested_attributes_for with hidden_field

Been searching stackoverflow for an answer to this one all day. I have a form to create a new topic. The first post should also be created with the topic. All is well except user_id is not being saved to the post.
Post Model
class Post < ActiveRecord::Base
belongs_to :topic
belongs_to :user
end
Topic Model
class Topic < ActiveRecord::Base
belongs_to :forum
belongs_to :user
has_many :posts
accepts_nested_attributes_for :posts
end
Post Controller
class PostsController < ApplicationController
def new
#post = Post.new
end
def create
#post = Post.new(post_params)
if #post.save
redirect_to topic_path(#post.topic_id)
else
render 'new'
end
end
private
def post_params
params.require(:post).permit(:content, :topic_id, :topic_name, :user_id)
end
end
Topic Controller
class TopicsController < ApplicationController
def new
#topic = Topic.new
#topic.posts.build
end
def create
#topic = Topic.new(topic_params)
if #topic.save
redirect_to #topic
else
render 'new'
end
end
private
def topic_params
params.require(:topic).permit(
:topic_name,
:forum_id,
:user_id,
posts_attributes: [:id, :content, :topic_id, :topic_name, :user_id ] )
end
end
new/topic View
<%= form_for(#topic) do |f| %>
<%= f.hidden_field :forum_id, :value => params[:forum_id] %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.label :topic_name %>
<%= f.text_field :topic_name %>
<%= f.fields_for :posts do |p| %>
<%= p.label :content %>
<%= p.text_area :content %>
<% end %>
<%= f.submit "Post Topic", class: "btn btn-large btn-success" %>
<% end %>
I am not entirely sure why the user_id is not being passed to the post. Hopefully someone smarter than me can help me learn what to do :)
UPDATE
I changed the strong params in my topics controller to this.
def topic_params
params.require(:topic).permit(
:topic_name,
:forum_id,
posts_attributes: [:content, :topic_id, :id, '_destroy' ] ).merge(:user_id => current_user.id, posts_attributes: [:user_id => current_user.id])
end
Now the user_id is working but none of the posts_attributes like :content are being saved. I'm having a lot of fun with this one..
Notice the form attributes that being generated in the browser, all the nested attributes for post have a prefix like topic[post_attributes], try change the form to:
<%= form_for(#topic) do |f| %>
<%= f.hidden_field :forum_id, :value => params[:forum_id] %>
<%= f.label :topic_name %>
<%= f.text_field :topic_name %>
<%= f.fields_for :posts do |p| %>
<%= p.hidden_field :user_id, :value => current_user.id %>
<%= p.label :content %>
<%= p.text_area :content %>
<% end %>
<%= f.submit "Post Topic", class: "btn btn-large btn-success" %>
<% end %>
Short answer, user_id is not in the posts_attributes since the only attributes there is content, which means that allowing other attributes like topic_id and topic_name is useless.
Now that we cleared that, you SHOULD NOT use a form input for the value of the creator of any model, because it's easy for anyone to tamper with the form and set the value to anything else, like other user's id. Alternatively, you should set the user_id value in the controller, in your case, the TopicsController. Here is the code:
def create
_params = topic_params.deep_merge(user: current_user, posts_attributes: {user: current_user})
#topic = Topic.new(_params)
if #topic.save
redirect_to #topic
else
render 'new'
end
end
and remove the user_id hidden field from the form.
UPDATE: Your last code update contains an error; it should be .merge(:user_id => current_user.id, posts_attributes: {:user_id => current_user.id}). You used a square brackets around :user_id => current_user.id instead of curly ones.

Why is my nested attributes form not working in rails?

I have a model called profile that has_many jobs. I am using the cocoon gem in order to allow users to make a profile, and then on a separate page make as many jobs as they'd like. The profile form is working fine. The job form, however, doesn't seem to actually be creating the jobs. Since a user needs to fill out a profile form before they can fill out a jobs form, by the time they get to the jobs form, it will automatically go to the update action in the profiles controller instead of the create. I'm pretty sure the problem is in the profiles controller. Here is the profiles controller:
def new
if current_user.profile
redirect_to edit_profile_path(current_user.profile_name)
else
#profile = Profile.new
end
end
def create
#profile = current_user.build_profile(profile_params)
#profile.save
if current_user.profile.invalid?
render :new, :status => :unprocessable_entity
else
redirect_to profile_path(current_user.profile_name)
end
end
def edit
#profile = current_user.profile
end
def update
#if current_user.profile.jobs.any?
#profile_save = current_user.profile.update_attributes(profile_params)
if current_user.profile.invalid?
#profile = current_user.profile
render :edit, :status => :unprocessable_entity
else
redirect_to profile_path(current_user.profile_name)
end
end
private
def profile_params
params.fetch(:profile, {}).permit(:title,
:category, :description, :state, :zip_code, :rate,
jobs_attributes: [:firm, :position, :category, :description,
:begin, :end, :_destroy])
end
I use fetch instead of require because otherwise I received an error saying the profile was not found. Here is the form:
<%= simple_form_for #profile do |f| %>
<h3> Jobs </h3>
<%= f.simple_fields_for :jobs do |job| %>
<%= render 'job_fields', :f => job %>
<% end %>
<%= link_to_add_association 'add job', f, :jobs %>
<%= f.submit %>
<% end %>
And here is the job_fields partial:
.nested-fields
<%= f.input :firm, label: "Firm" %> <br>
<%= f.input :position, label: "Position" %> <br>
<%= f.input :category, label: "Category"%><br>
<%= f.input :begin, label: "Beginning", collection: 1960..2013 %><br>
<%= f.input :end, label: "End", collection: 1960..2013 %>
<%= f.input :description, label: "Description"%><br>
<%= link_to_remove_association "remove task", f %>
The problem could also be that I translated from HAML to ERB and I think I did it incorrectly.
Also, all profiles actually belong to a user, but i don't think that should make a difference. Thanks in advance for the help!
If the issue is that you want to call the create method for Jobs, you'll need to modify your form to explicitly use the post method. Something like:
<%= simple_form_for #profile, :url => new_jobs_path, :method => :post do |f| %>
<h3> Jobs </h3>
<%= f.simple_fields_for :jobs do |job| %>
<%= render 'job_fields', :f => job %>
<% end %>
<%= link_to_add_association 'add job', f, :jobs %>
<%= f.submit %>
<% end %>

Rails 4 strong params and nested form

I'm building a simple app (Ruby 2.0.0 and Rails 4) where a user can create a project and for each project create multiple screens. When creating a screen the user can upload a screenshot, that refer to a its own model (I do this to handle multiple versions of the same screen).
When creating the screen, the screenshot doesn't seem to be created because of a permission problem. Here's the server log:
Processing by ScreensController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"kezaGADsaLmY/+zozgbjEe5UfdeqRPg58FCf1qzfHxY=", "screen"=>{"project_id"=>"24", "name"=>"Billing", "description"=>"This is the page where a user will enter their credit card information", "screenshot"=>{"image"=># <ActionDispatch::Http::UploadedFile:0x007fcdce25b2c0 #tempfile=#<Tempfile:/var/folders/pv/srwrv0qj35b0hsxkt42l_z500000gn/T/RackMultipart20131007-91790-tewse9>, #original_filename="fb-banner.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"screen[screenshot][image]\"; filename=\"fb-banner.png\"\r\nContent-Type: image/png\r\n">}}, "commit"=>"Create Screen"}
Unpermitted parameters: screenshot
These are my models:
Screen
class Screen < ActiveRecord::Base
belongs_to :project
has_many :screenshots
validates :name, presence: true
accepts_nested_attributes_for :screenshots
end
Screenshot
class Screenshot < ActiveRecord::Base
belongs_to :screen
end
This is my screens_controller:
class ScreensController < ApplicationController
before_action :set_screen, only: [:show, :edit, :update, :destroy]
def index
#screens = Screen.all
end
def show
end
def new
#screen = Screen.new(:project_id => params[:project_id])
#screen.screenshot.build
end
def edit
end
def create
#screen = Screen.create(screen_params)
if #screen.save
flash[:notice] = "A new screen has been added to this project"
redirect_to [#screen.project]
else
render :action => 'new'
end
end
def update
#screen = Screen.find(params[:id])
if #screen.update_attributes(screen_params)
flash[:notice] = "The screen has been successfully updated"
redirect_to [#screen.project]
else
render :action => 'edit'
end
end
def destroy
#screen = Screen.find(params[:id])
#screen.destroy
flash[:notice] = "Successfully destroyed screen"
redirect_to [#screen.project]
end
private
def set_screen
#screen = Screen.find(params[:id])
end
def screen_params
params.require(:screen).permit(:project_id, :name, :description, screenshot_attributes: [ :id, :screen_id, :image, :version ])
end
end
And finally this is the form:
<%= form_for #screen, :html => { :multipart => true } do |f| %>
<% if #screen.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#screen.errors.count, "error") %> prohibited this screen from being saved:</h2>
<ul>
<% #screen.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.hidden_field :project_id %>
</div>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<%= f.fields_for :screenshot do |s| %>
<%= s.hidden_field :screen_id, :value => #screen.id %>
<%= s.hidden_field :version, :value => "1" %>
<%= s.label :image %><br>
<%= s.file_field :image %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I hope this is enough to help me spot the problem. I'm a newbie when it comes to programming, so any help is more than welcome.
I recently worked through something similar, and this is what seemed to work...
Change your fields_for to plural:
<%= f.fields_for :screenshots do |s| %>
And also, make your params
def screen_params
params.require(:screen).permit(:project_id, :name, :description, screenshots_attributes: [ :id, :screen_id, :image, :version ])
end
Also, you need to update your new action to make screenshots plural, like so:
def new
#screen = Screen.new(:project_id => params[:project_id])
#screen.screenshots.build
end

Resources