param is missing or the value is empty: user_club - rails - ruby-on-rails

I want to call create action of controller user_clubs and I did this way:
View Clubs
<button>
<%= link_to "Join Club", user_clubs_path(:user_id => current_user.id, :club_id => #club.id, :join_date => Date.current), :method => :post %>
</button>
Controller user_clubs
def create
#user_club = UserClub.new(user_club_params)
respond_to do |format|
if #user_club.save
format.html { redirect_to #user_club, notice: 'User club was successfully created.' }
format.json { render :show, status: :created, location: #user_club }
else
format.html { render :new }
format.json { render json: #user_club.errors, status: :unprocessable_entity }
end
end
end
def user_club_params
params.require(:user_club).permit(:user_id, :club_id, :join_date) --->**Error here**
end
Error information
app/controllers/user_clubs_controller.rb:75:in user_club_params'
app/controllers/user_clubs_controller.rb:28:increate'
Request
Parameters:
{"_method"=>"post",
"authenticity_token"=>"5Grhb+LIGt9B8XbnEcvg7BZQlDE935KO/aeikZoqxYs=",
"club_id"=>"1",
"join_date"=>"2014-11-17",
"user_id"=>"2"
}
Clubs and UserClubs are different. Club is a model that represents a team of people and user_clubs is the model that represents the many-to-many relationship between Users and Clubs.
First, can someone explain me how the call to user_clubs_path followed by the arguments know that has to go to the action create of user_clubs controller?
In second, the objective problem, why is this an error?

First question
Because of your routes definition, type into a terminal:
rake routes
And you'll see all generated routes and its associated helpers. First column (rake output) references the named helper: user_clubs => user_clubs_path):
Second question
You should add the parameters into user_club key, because you're requiring (by strong_parameters) this "scope" params.require(:user_club):
user_clubs_path(:user_club => {:user_id => current_user.id, :club_id => #club.id, :join_date => Date.current})
You'll receive in the controller:
{
"_method" => "post",
"authenticity_token" => "...",
"user_club" => {
"club_id" => "1",
"join_date"=> "2014-11-17",
"user_id"=> "2"
}
}

The parameters need to be nested under the user_club key. Try this instead:
user_clubs_path(:user_club => {:user_id => current_user.id, :club_id => #club.id, :join_date => Date.current})

Related

Render hash with objects belonging to instance

I have theses associations:
# Post
has_many :photos
# Photos
belongs_to :post
In my show action, in the post controller, I have this:
def show
#post = Post.find(params[:id])
#photos = #post.photos
render json: {post: #post.id }
end
However, I'd like the json to include the photos of the post, and get something like this:
{
post: 14,
photos {
photo1 {
url: /myURL/,
id: 1
},
photo1 {
url: /myURL/,
id: 2
}
}
}
I found many posts on how to do the opposite but not this. How should I approach this ?
You can do it this way:
render :json => #post, :include => [:photos => {:only => :url, :id}]

Rails after create not functioning as expected

In my Case model (case.rb) I have a few after_create callbacks. One of which is not functioning as expected.
By that I mean when I run it in the console, it works, but when creating it in the controller via an HTTP request, it does not.
Model code (the problem is with :create_case_users not working):
after_create -> { redis_check(true) },
:create_case_users,
:create_manager,
:pusher_trigger
And the create_case_users method:
def create_case_users
cus = CaseUser.where(:case_id => self.id, :is_age => 1)
cus.each do |cu|
connections = Connection.where({ :cases => 1, :con_id => cu.user_id })
connections.each do |connection|
if connection.user_id && connection.connection_id
case_user = CaseUser.new
case_user.case_id = self.id
case_user.user_id = connection.user_id
case_user.email = connection.cases_emails
case_user.is_age = 0
case_user.cm = 0
case_user.save!
end
end
end
end
When running the above snippet in the console of my app, specifying the Case to run it for, it works & creates the records I expect.
When I POST to /api/v1/cases, it hits this controller action:
#case = Case.new(case_params)
#case.current_user(#current_user)
if #case.save
render :json => #case,
:root => "case",
:status => :created,
:location => #case,
:serializer => CaseShowSerializer,
:current => #current_user
else
render :json => #case.errors,
:status => :unprocessable_entity
end
What could be the problem? The after create callback after create_case_users runs and functions as expected, meaning create_case_users isn't returning false.
Edit:
When running Case.find(500).create_case_users in the console it works.

Rails json response including nested reources and their methods

Hello i"m trying desperately to render json that includes methods within my included nested resources. I tried many variants but just can't get that thing to run.
This is what i have:
format.json {render json: #user, :include => [ :votes, :petitions, :roles ] }
And that is what i had hoped to work
format.json {render json: #user, :include => {
:votes => { :methods => [ :status, :count_users_voted ] },
:petitions => { :methods => [:status, :count_users_voted] },
:roles
}
}
Any hints anyone?
Add something like this to your User model:
def as_json(options = { })
super((options || { }).merge({
:methods => [:agrees, :disagrees]
}))
end
def agrees
self.liked_by_count
end
def disagrees
self.disliked_by_count
end
Pretty straight forward, I hope this helps

JSON Rendering: How to include the opening bracket description?

I have some Ruby code that is putting out JSON like this:
def nearby
##bathrooms = Bathroom.geo_scope(:origin =>[params[:lat],[params[:lon]]], :within => 5)
lat = params[:lat]
lon = params[:lon]
##bathrooms = Bathroom.geo_scope(:within => 5, :origin => [45.580639,-122.677682], :order=>'distance')
#bathrooms = Bathroom.geo_scope(:within => 3, :origin => [lat,lon], :order=>'distance')
respond_to do |format|
format.json { render :json => #bathrooms }
format.js { render :nothing => true }
end
end
The result is something like this:
[{"ID":129,"access":"1","avail":"0","bathroomtype":"0","city":"PORTLAND","comment":"","country":"US","created":"0000-00-00 00:00:00","directions":"The two bathrooms are in the long hallway at the back of the restaurant, past the bar.","distance":"2.94986114636676","lat":"45.539217","lon":"-122.661795","modifed":"0000-00-00","name":"Echo","postal":"97212-3727","slug":"echo-portland170","source":"","state":"OR","street":"2225 NE Martin Luther King Jr. Blvd"},
What I don't know how to do is to name the set? For example, after the first enclosing bracket I would like to name the set bathrooms. How can I do this is Rails?
Try:
render json: { bathrooms: #bathrooms }
It looks like #bathrooms is a list, so you can't assign keys to elements in lists. You'll need to make a map first. For example, if you only want the first element:
format.json { render :json => {:bathrooms => #bathrooms[0]} }
To set all list elements:
format.json { render :json => {:bathrooms => #bathrooms} }

How to make errored inputs prepopulate with previously inputted data

I'm making a custom AJAX form.
If a user fills out half of the form, it will fail wanting the other half fulfilled.
For some odd reason, the form is not pre-populating with at least what they had already inputted.
Because it's not doing this, how can I manually tell it to do so? When the form returns, the Object it verified is still accessible, so I can withdraw information from it.
a sample of the form
- form_for CardSignup.new do |f|
- unless #card_signup.nil?
- if !#card_signup.errors.empty?
.prefix_1.grid_4
- #card_signup.errors.full_messages.each do |error|
.warning
= error
%br/
.grid_2.prefix_1{:style => "width: 166px;"}
= f.text_field :first_name, :style => "width: 166px;", :value => "first name", :rel => "first name"
%div{:class => 'error_message'}
my Create method
def create
if params[:user] && current_user.admin
#card_signup = User.find(params[:user]).build_card_signup(params[:card_signup])
else
#card_signup = current_user.build_card_signup(params[:card_signup])
end
if #card_signup.valid?
respond_to do |wants|
#wants.html { redirect_to disclaimer_card_signup_path, :locals => { :card_signup => #card_signup } }
wants.json { render :json => { :html => (render_to_string :partial => 'disclaimer') } }
end
else
respond_to do |wants|
#wants.html { redirect_to new_card_signup_path }
wants.json { render :json => {:errors => #card_signup.errors, :html => (render_to_string :partial => '/card_signups/new_form') } }
end
end
end
You're doing this:
form_for CardSignup.new
which will instantiate a new CardSignup object every time you render the form. Move this into the new action and in the create action do this:
#card_signup = CardSignup.new(params[:card_signup])
This will pass the half-filled object back to the form and you'll get the already populated fields.

Resources