Adding single item to rails has_many :through - ruby-on-rails

I have a has_many :thorugh relationship between customers and software products they own.
# company.rb
class Company < ActiveRecord::Base
has_many :company_sources
has_many :sources, :through => :company_sources
end
# source.rb
class Source < ActiveRecord::Base
has_many :company_sources
has_many :companies, :through => :company_sources
end
# company_source.rb
class CompanySource < ActiveRecord::Base
belongs_to :company
belongs_to :source
end
The controllers are the default rails g scaffold <name> files
I need a selection form on the company edit page that will allow the addition of a single source to the company_source table.
The closest I can get is using the selection form helper, however that will overwrite the previous addition when I go to add a new item.
I've been playing with this for quite a few hours now and I can't seem to get the form/routes/controller right.
This is the form I'm playing with at the time of writing
<table>
<% #company.sources.each do |source| %>
<tr><%= source.name %></tr>
<% end %>
<tr>
<%= form_for #company do |f| %>
<td>
<%= select("source", "id", Source.all.collect {|p| [ p.name, p.id ]}, { include_blank: true })%>
</td>
<td>
<%= f.submit "Add Source" %>
</td>
<% end %>
</tr>
</table>
Full controller (again, at time of writing)
class CompaniesController < ApplicationController
before_action :set_company, only: [:show, :edit, :update, :destroy]
# GET /companies
# GET /companies.json
def index
#companies = Company.all
end
# GET /companies/1
# GET /companies/1.json
def show
end
# GET /companies/new
def new
#company = Company.new
end
# GET /companies/1/edit
def edit
end
# POST /companies
# POST /companies.json
def create
#company = Company.new(company_params)
respond_to do |format|
if #company.save
format.html { redirect_to #company, notice: 'Company was successfully created.' }
format.json { render :show, status: :created, location: #company }
else
format.html { render :new }
format.json { render json: #company.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /companies/1
# PATCH/PUT /companies/1.json
def update
respond_to do |format|
if #company.update(company_params)
format.html { redirect_to #company, notice: 'Company was successfully updated.' }
format.json { render :show, status: :ok, location: #company }
else
format.html { render :edit }
format.json { render json: #company.errors, status: :unprocessable_entity }
end
if (params[:source_id])
#company.source << Source.find(params[:source_id])
end
end
end
# DELETE /companies/1
# DELETE /companies/1.json
def destroy
#company.destroy
respond_to do |format|
format.html { redirect_to companies_url, notice: 'Company was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_company
#company = Company.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def company_params
params.require(:company).permit(:name, :description, :source_id)
end
end

In the update action, I propose not doing #company.update, and instead doing:
company_source = CompanySource.create!(company: #company, source: Source.find(source_id)
(Warning: There might be errors in the code, which you should be able to correct fairly easily)
So, the update action would look like:
def update
respond_to do |format|
company_source = CompanySource.new(company: #company, source_id: params[:source_id])
if company_source.save
format.html { redirect_to #company, notice: 'Company was successfully updated.' }
format.json { render :show, status: :ok, location: #company }
else
format.html { render :edit }
format.json { render json: company_source.errors, status: :unprocessable_entity }
end
end
end
Although this shifts the perspective to that of the CompanySource despite being inside the CompaniesController, what you are really wanting to do is create a new CompanySource. I think this is the most straightforward way of looking at it.
This will ensure correct updates of the Compnay-Source relationship.

Related

Unpermitted parameter using fields_for Rails

I got such message in console when trying to use fields_for in Rails:
Parameters: .... "task"=>{"task_name"=>"111", "tag"=>{"tag_text"=>"222"}}, "commit"=>"Save"}
Unpermitted parameter: tag
My models with has_many and belongs_to:
class Task < ActiveRecord::Base
has_many :tags
accepts_nested_attributes_for :tags
end
class Tag < ActiveRecord::Base
belongs_to :task
end
Form helper for new/edit page:
<%= form_for(#task) do |f| %>
<%= f.text_field :task_name %>
<%= f.fields_for([#task, #task.tags.build]) do |t| %>
<%= t.text_field :tag_text %>
<% end %>
<%= f.submit 'Save' %>
<% end %>
My Task Controller (I used scaffold to generate it, and its mostly default)
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
def index
#tasks = Task.all
end
def show
end
def new
#task = Task.new
#task.tags.build
end
def edit
#task.tags.build
end
def create
#task = Task.new(task_params)
respond_to do |format|
if #task.save
format.html { redirect_to #task, notice: 'Task was successfully created.' }
format.json { render :edit, status: :created, location: #task }
else
format.html { render :new }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to edit_task_path, notice: 'Task was successfully updated.' }
format.json { render :edit, status: :ok, location: #task }
else
format.html { render :edit }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def destroy
#task.destroy
respond_to do |format|
format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
#task = Task.find(params[:id])
end
def task_params
params.require(:task).permit(:task_name, :task_sum, :status_id, :user_id, :target_release_id, tag_attributes: [:tag_text, :task_id])
end
end
I think the problem is in the way you use fields_for. Try to make this way:
<%= f.fields_for :tags do |t| %>
That way the param tags_attributes will be send and every thing should be fine.
EDIT
Also, if you are using Rails 5, you need to set the belongs_to as optional so the accepts_nested_attributes_for can work properly. So:
class Tag < ActiveRecord::Base
belongs_to :task, optional: true
end
And the parameters sanitization in your tasks_controller.rb you do not need tag_id under tags_attributes:
def task_params:
params.require(:task).permit(:task_name, tags_attributes: [:tag_text])
end
EDIT
I think I found your problem. Try to put tags_attributes instead of tag_attributes in your task_paramsmethod.

Item in Active Record not rendering correctly - Rails 4.2

Not quite sure if 'Active Record' is the right term. The DB? Postgres?
I'm following through Rails Tutorial and having a very frustrating issue. I've found quite a few posts on SO with people struggling, but majority of them went way off base for the answers, so I'm trying to find out what's wrong with my example.
My User Controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
#users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:name, :email)
end
end
My User Model
class User < ApplicationRecord
has_many :micropost
validates :name, presence: true
validates :email, presence: true
end
My Microposts Model
class Micropost < ApplicationRecord
belongs_to :user
validates :content, length: { maximum: 140 },
presence: true
end
My Microposts Controller
class MicropostsController < ApplicationController
before_action :set_micropost, only: [:show, :edit, :update, :destroy]
# GET /microposts
# GET /microposts.json
def index
#microposts = Micropost.all
end
# GET /microposts/1
# GET /microposts/1.json
def show
end
# GET /microposts/new
def new
#micropost = Micropost.new
end
# GET /microposts/1/edit
def edit
end
# POST /microposts
# POST /microposts.json
def create
#micropost = Micropost.new(micropost_params)
respond_to do |format|
if #micropost.save
format.html { redirect_to #micropost, notice: 'Micropost was successfully created.' }
format.json { render :show, status: :created, location: #micropost }
else
format.html { render :new }
format.json { render json: #micropost.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /microposts/1
# PATCH/PUT /microposts/1.json
def update
respond_to do |format|
if #micropost.update(micropost_params)
format.html { redirect_to #micropost, notice: 'Micropost was successfully updated.' }
format.json { render :show, status: :ok, location: #micropost }
else
format.html { render :edit }
format.json { render json: #micropost.errors, status: :unprocessable_entity }
end
end
end
# DELETE /microposts/1
# DELETE /microposts/1.json
def destroy
#micropost.destroy
respond_to do |format|
format.html { redirect_to microposts_url, notice: 'Micropost was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_micropost
#micropost = Micropost.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def micropost_params
params.require(:micropost).permit(:content, :user_id)
end
end
My show.html.erb
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= #user.name %>
</p>
<p>
<strong>Email:</strong>
<%= #user.email %>
<% if #user.micropost.any? %>
<%= #user.micropost.first %>
<% end %>
</p>
<%= link_to 'Edit', edit_user_path(#user) %> |
<%= link_to 'Back', users_path %>
When I load a Users page (6 or 7 in my case) I am seeing 'something' being outputted in this format, but it's showing
Which I feel like is an Active Record (?) index? I'm not sure how to get it to show the first (or any) Micropost of a User.
In some solutions I saw people used render #user.micropost but I get an issue about partials (Which I'm familiar with) but the tutorial says you should be able to use the syntax used previously (aka #user.email ) to solve it. So I feel I'm over complicating it?
My issue was I needed to use
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= #user.name %>
</p>
<p>
<strong>Email:</strong>
<%= #user.email %>
<% if #user.micropost.any? %>
<%= #user.micropost.first.content %>
<% end %>
</p>
<%= link_to 'Edit', edit_user_path(#user)
%> |
<%= link_to 'Back', users_path %>
I should have realized when it was reporting a hash value.
you can't be rendering the show page because if you did you would get a no method or for nil class.
Your show action has no instance variable called #user.
For your show to display data you need a user object. In your case you have none.
So in your show method, add this:
#user.find_by(params[:id])
That will find the user 6 or 7 and allow you to call #
Can you paste the url from the browser so I can see where you actually are?

Can't Display a value from my rails model

I'm new to Ruby on Rails and I started with a scaffold and added another model manually. I can't seem to get the values from the model I manually generated to display in my index view.
My first model is for Golf Courses names, city, par, and hole_id. The second model is the amount of holes for each course. For some reason I can't get the hole amount to display Below is my code.
Models
class Course < ActiveRecord::Base
has_many :holes
end
class Hole < ActiveRecord::Base
belongs_to :course
end
Controller
class CoursesController < ApplicationController
before_action :set_course, only: [:show, :edit, :update, :destroy]
# GET /courses
# GET /courses.json
def index
#courses = Course.all
#holes = Hole.all
end
# GET /courses/1
# GET /courses/1.json
def show
end
# GET /courses/new
def new
#course = Course.new
end
# GET /courses/1/edit
def edit
end
# POST /courses
# POST /courses.json
def create
#course = Course.new(course_params)
respond_to do |format|
if #course.save
format.html { redirect_to #course, notice: 'Course was successfully created.' }
format.json { render :show, status: :created, location: #course }
else
format.html { render :new }
format.json { render json: #course.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /courses/1
# PATCH/PUT /courses/1.json
def update
respond_to do |format|
if #course.update(course_params)
format.html { redirect_to #course, notice: 'Course was successfully updated.' }
format.json { render :show, status: :ok, location: #course }
else
format.html { render :edit }
format.json { render json: #course.errors, status: :unprocessable_entity }
end
end
end
# DELETE /courses/1
# DELETE /courses/1.json
def destroy
#course.destroy
respond_to do |format|
format.html { redirect_to courses_url, notice: 'Course was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_course
#course = Course.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def course_params
params.require(:course).permit(:name, :city, :hole_id)
end
end
View
<p id="notice"><%= notice %></p>
<p>
<strong>Name:</strong>
<%= #course.name %>
</p>
<p>
<strong>City:</strong>
<%= #course.city %>
</p>
<p>
<strong>Hole:</strong>
<%= #course.holes %>
</p>
<%= link_to 'Edit', edit_course_path(#course) %> |
<%= link_to 'Back', courses_path %>
<%= #course.holes %> gives you an ActiveRecord_Associations_CollectionProxy
You need to ask for its size, length or its count to get the total amount of holes that belong to #course which means you have to say #course.holes.size, #course.holes.length or #course.holes.count. Check the documentation for the differences between these three.

FIle upload with Carrier wave returning :nil

I'm attempting to add carrierwave to my application to handle attachments from users (pdf, doc, etc - not images). I've viewed several tutorials and while it seems to be working, I am not able to access the attachment through link_to method or by following the url carrierwave creates. I'm running into two odd things when using my application:
1) The link preview (referring to the popup in the bottom left in chrome showing the destination of the link) only shows localhost::model/id, not the url that is in the uploader
2) When I view a record in the rails console, the column shows nil. I have added this into my permitted params in the controller.
My controller:
class Cms484sController < ApplicationController
before_action :set_cms484, only: [:show, :edit, :update, :destroy]
# GET /cms484s
# GET /cms484s.json
def index
#cms484s = Cms484.all
end
# GET /cms484s/1
# GET /cms484s/1.json
def show
end
# GET /cms484s/new
def new
#cms484 = Cms484.new
end
# GET /cms484s/1/edit
def edit
end
# POST /cms484s
# POST /cms484s.json
def create
#cms484 = Cms484.new(cms484_params)
respond_to do |format|
if #cms484.save
format.html { redirect_to #cms484, notice: 'Cms484 was successfully created.' }
format.json { render :show, status: :created, location: #cms484 }
else
format.html { render :new }
format.json { render json: #cms484.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /cms484s/1
# PATCH/PUT /cms484s/1.json
def update
respond_to do |format|
if #cms484.update(cms484_params)
format.html { redirect_to #cms484, notice: 'Cms484 was successfully updated.' }
format.json { render :show, status: :ok, location: #cms484 }
else
format.html { render :edit }
format.json { render json: #cms484.errors, status: :unprocessable_entity }
end
end
end
# DELETE /cms484s/1
# DELETE /cms484s/1.json
def destroy
#cms484.destroy
respond_to do |format|
format.html { redirect_to cms484s_url, notice: 'Cms484 was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cms484
#cms484 = Cms484.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cms484_params
params.require(:cms484).permit(:supplier_name, :supplier_addr, :supplier_city, :supplier_state, :supplier_zip, :frm_date, :document)
end
end
My uploader:
class FileUploader < CarrierWave::Uploader::Base
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
My form: (abbreviated)
<%= f.file_field :file, multiple: true %>
<div class="actions">
<input type="submit" name="commit" value="Complete Cms484" />
</div>
<% end %>
</body>
</html>
My view:
<p>
<strong>Sup name:</strong>
<%= #cms484.supplier_name %>
</p>
<%= link_to 'Document', #cms484.document.url %> |
<%= link_to 'Edit', edit_cms484_path(#cms484) %> |
<%= link_to 'Back', cms484s_path %>
Any ideas?
Carrierwave relies on the naming convention of your uploader class. In your case you named it FileUploader.
Adjust your permitted attributes from :document to :file
def cms484_params
params.require(:cms484).permit(:supplier_name, :supplier_addr, :supplier_city, :supplier_state, :supplier_zip, :frm_date, :file)
end
In your view
<%= link_to 'Document', #cms484.file_url %>

Create and Update record from same field with RoR

I'm building a rails app that will be used by people to log how many steps they took on a given week.
The functionality of the application includes an activity logger that a person can enter steps into, click a week shown on a calendar, and click submit. The application will then create a record of the person's id, when the steps were taken, and how many steps. The same step logger should update the step count if the same user logs a different number of steps on a day.
I'm having trouble getting the logic into the controller to check if a step record exists that has the same user_id and step_date as the step being added.
I've looked into "find_or_initialize_by"/"find_or_create_by" but haven't had much luck.
Can anyone point me in the right direction? Code below.
Logging form (_activityLog.html.erb):
<%= simple_form_for Step.new do |f| %>
<%= f.hidden_field :user_id, :value => #user.id %>
<%= f.hidden_field :challenge_id, :value => "1" %>
<div class="input-group">
<span class="input-group-addon" id="basic-addon2">Steps I've Taken:</span>
<%= f.input :step_count, label: false, id: "step_count", class: "form-control", required: true %>
</div>
<div id="weekpicker"></div>
<%= f.input :step_date, as: :hidden, input_html: { class: 'week' } %>
<%= f.button :submit, "Log Activity", class: "submit btn-block", id: "submitWeekly" %>
<% end %>
Steps Controller (steps_controller.rb)
class StepsController < ApplicationController
before_action :set_step, only: [:show, :edit, :update, :destroy]
# GET /steps
# GET /steps.json
def index
#steps = Step.all
end
# GET /steps/1
# GET /steps/1.json
def show
redirect_to(:back)
end
# GET /steps/new
def new
#step = Step.new
end
# GET /steps/1/edit
def edit
end
# POST /steps
# POST /steps.json
def create
#step = Step.new(step_params)
respond_to do |format|
if #step.save
format.html { redirect_to #step, notice: 'Step was successfully created.' }
format.json { render :show, status: :created, location: #step }
else
format.html { render :new }
format.json { render json: #step.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /steps/1
# PATCH/PUT /steps/1.json
def update
respond_to do |format|
if #step.update(step_params)
format.html { redirect_to #step, notice: 'Step was successfully updated.' }
format.json { render :show, status: :ok, location: #step }
else
format.html { render :edit }
format.json { render json: #step.errors, status: :unprocessable_entity }
end
end
end
# DELETE /steps/1
# DELETE /steps/1.json
def destroy
#step.destroy
respond_to do |format|
format.html { redirect_to steps_url, notice: 'Step was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_step
#step = Step.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def step_params
params.require(:step).permit(:user_id, :challenge_id, :step_date, :step_count)
end
end
Step Model (step.rb)
class Step < ActiveRecord::Base
belongs_to :user
belongs_to :challenge
end
Maybe something like this?
def create
# ... leaving some stuff out :)
#step = Step.where(user_id: params[:user_id], step_date: params[:step_date]).first_or_initialize(step_params) # or first_or_create
# ... other code here (leaving more stuff out)
end

Resources