In a rails project I have two entities, Users and Institutions, they have a many-to-many relationship.
The views for them are set up to create new users and institutions but I want to have another view for linking the two.
In rails console all I have to do is
myuser.institutions << the_institution_i_just_created
The controller can do some of the work but how do I handle the submissions and the forms? I want to use a selection box so that the input is limited to the Institutions already in existence.
<select id="institution_selection" name="institution_sel">
<% selections = []
Institution.all.each do |institution|
pair = [institution.name, institution.id]
selections.concat([pair])
end
%>
<%= options_for_select(selections) %>
</select>
So the question in summary is how do I map this submission to an object so that in the controller I can do add it to the relation?
The solution was:
Alright, so this is the solution I came up with, I'm sure there is a better way to go about it and I'll continue to look into it but at least I got something close to what I was aiming for
def test
if !session[:user]
redirect_to users_path, notice: "Please login first"
end
if params[:institution]
#user = User.find(session[:user])
#institution = Institution.find(params[:institution][:id])
#user.institutions << #institution
redirect_to #user, notice: "Institution was successfully added "
end
end
and for the view
<%= form_tag("/users/test", :method => "post") do %>
<%= collection_select :institution, :id, Institution.all, :id, :name %>
<%= submit_tag("Search") %>
<% end %>
Use collection_select
<% from for #instancevar do |form| %>
<%= form.collection_select :institution_id, Institution.all, :id, :name %>
# Do other stuff....
<% end %>
Related
I have a form where users look for a particular bill by some attributes of that bill, namely the "Congress Number", "Bill Type", and "Bill Number", as in 114-H.R.-67 . I want to "show" the appropriate bill, but to do that I have get the appropriate bill model in a separate action which I've called "find_by_attributes". Inside this action I perform:
#bill = Bill.find_by( params ).first
which correctly acquires the appropriate bill's id.
Now I simply want to redirect to the "show" method of this bill, as in the url
".../bills/[#bill.id]"
As of right now, at the end of my "find_by_attributes" action I do
redirect_to bills_path(#bill)
which correctly loads the show.html.erb with #bill, but does not change the url (the url is still shows the "find_by_attributes" action followed by a long query-string, instead of the clean "/bills/[:bill_id]".
How can I restructure my code to achieve the neat redirect that I desire?
Full code below:
THE FORM
<%= form_tag("bills/find_or_create", :method => :get ) do |f| %>
<%# render 'shared/error_messages', object: f.object %>
<%= fields_for :bill do |ff| %>
<%= ff.label :congress, 'Congress (i.e. 114)' %>
<%= ff.number_field :congress, class: 'form-control' %>
<%= ff.select :bill_type, options_for_select(
[['House of Representatives', 'hr'],
['Senate', 's'],
['House Joint Resolution', 'hjres'],
['Senate Joint Resolution', 'sjres'],
['House Concurrent Resolution', 'hconres'],
['Senate Concurrent Resolution', 'sconres'],
['House Resolution', 'hres'],
['Senate Resolution', 'sres']]
)
%>
<%= ff.label :bill_number, 'Bill number (i.e. 67)' %>
<%= ff.number_field :bill_number, class: 'form-control' %>
<% end %>
<%= submit_tag "Submit", class: "btn btn-primary" %>
<% end %>
THE CONTROLLER ACTIONS
def find_by_attributes
#bill = Bill.where(bill_params).first_or_create(bill_attributes)
redirect_to bills_path(#bill)
end
def show
puts bill_params
if params[:bill]
#bill = Bill.where(bill_params).first_or_create do |bill|
bill.attributes = bill_attributes
end
else
#bill = Bill.find(params[:id])
end
#subjects = Subject.where("bill_id = ?", #bill[:id])
#bill_comments = Comment.where("target = ?", #bill[:id])
end
ROUTES FILE
...
resources :bills do
get :find_by_attributes
end
...
EDIT
I make use of the turbolinks gem in my rails application.
the thing I see here is that you are calling to
redirect_to bills_path(#bill)
that in theory is not the show path, you just need to remove the "s"
redirect_to bill_path(#bill)
and as a side comment, in this line, you don't need the first part, because find_b, finds the first record matching the specified conditions, you can remove that part.
#bill = Bill.find_by( params )
So I have this structure of application: a Game model which has many Allies and many Enemies.
I want to create a custom action for Game dedicated to create and submit enemies and allies.
So in the view I will have 2 fields_for that you can submit at the same time.
I have never created custom routes and actions or submitted 2 children forms in the same page.
Anyone know how I could do this ? Thanks
routes.rb
#this route shows the form
get 'create-players/:id', to 'game#new_players', as: :new_players
# this route recieves the form post submission
post 'create-players/:id', to 'game#create_players', as: :create_players
app/controllers/game_controller.rb:
def new_players
#game = Game.find(params[:id])
end
def create_players
#do whatever you want with the params passed from the form like
#allies = Ally.create(game_id: params[:id], name: params[:ally_fields][:name])
#enemies = Enemy.create(game_id: params[:id], name: params[:enemy_fields][:name])
#game = Game.find(params[:id])
end
app/views/game/new_players.html.erb:
<%= form_tag(create_players_paths, #game.id), method: 'POST') do %>
<% #...fields you have on models, perhaps %>
<% fields_for :ally_fields do |f|
<%= f.text_field :name, nil, placeholder: "Ally name", required: true
<% end % >
<% fields_for :enemy_fields do |f|
<%= f.text_field :name, nil, placeholder: "Enemy name", required: true
<% end % >
<%= submit_tag "create players", class: "submit" %>
<% end %>
app/views/game/create_players.html.erb:
<h1> Woah an allie and an enemy have been added to game <%= #game.id %></h1>
<p> Lets see some blood!</p>
Of course, you should enforce verifications on the input and before processing the post submission. Usually you'll want to use established relationships between objects, so that you can do on the view #model = Modelname.new then, form_for #object and have validations and error messages accessible in a much cleaner way.
Let's say I have a bunch of cards listed on my wall show action. When you interact with a card (click it for example), I want to update that card's attributes.
I'm currently doing this by getting the card's attributes with Javascript, adding them to a card form and submitting the form remotely.
I have the card's ID, but how do I tell the form which card I want to update?
What should the form and controller update action look like?
This is what I have so far
Form
<%= form_for(#card, remote: true) do |f| %>
<%= f.text_field :list_id %>
<%= f.text_field :order %>
<% end %>
Controller
def update
#card = Card.find(params[:id])
if #card.update_attributes(shared_params)
redirect_to edit_card_path(#card, format: :html)
else
render :edit
end
end
You can use the same new template for edit too. The only requirement here is the object you wanted to edit.
So, first get you edit action ready in controller as
def edit
#card = Card.find(params[:id])
end
edit/new.html.erb
<%= form_for(#card, remote: true) do |f| %>
<%= f.text_field :list_id %>
<%= f.text_field :order %>
<% end %>
In the cards show page, add a link to the edit action as
<%= link_to "Edit", edit_card_path(card.id) %>
I'm working on a dynamic form in a Rails app, and I need to insert a variable number of records into a model in a single form submission. I've done this using PHP -> MySQL/Postgres before, but I have no idea how to do it in Rails.
Ultimately, users should be able to create any number of records to be inserted, but in my example below, I'm limiting it to 2... let me see if I can do that, first...
Here's the form - the ids all get a unique suffix because they are being populated dynamically from localStorage objects on submission.
new.html.erb
<%= form_for #entry, html: {id: :new_entry_form} do |f| %>
<% for i in 0..1 %>
<%= f.text_field :name, :id => 'name_#{i}' %>
<%= f.text_field :day, :id => 'day_#{i}' %>
<% end %>
<% end %>
Here's the associated controller - I'm sure that this is missing something, but I don't know what.
def new
#entry = Entry.new
end
def create
#entry = Entry.create(entry_params)
redirect_to "http://localhost:3000/entries"
end
private
def entry_params
params.require(:entry).permit(:name, :day)
end
Any help would be much appreciated.
Follow this link it shows how to create multiple object in one form submit:
http://vicfriedman.github.io/blog/2015/07/18/create-multiple-objects-from-single-form-in-rails/
I have list dropdown list in my activeadmin that populates the recipe and menu. I'm trying to override the create method but it is not working
<%= semantic_form_for [:admin, #menu_recipe] do |f| %>
<p>
<%= f.collection_select :recipe_id,
Recipe.all,:id,:name,:prompt => true%>
</p>
<p>
<%= f.collection_select :menu_id,
Menu.all,:id,:name,:prompt => true%>
</p>
<%= f.buttons :commit %>
<%end%>
Whenever I try to catch the and create or group it, it returns with a Couldn't find Recipe without an ID error
my active admin controller which i override is
ActiveAdmin.register MenuRecipe do
menu :parent => "Manage Package"
form :partial => "menu_recipe"
controller do
def new
new! do |format|
#menu_recipe = MenuRecipe.new
end
end
def create
create! do |format|
recipe = Recipe.find(params[:recipe_id])
menu = Menu.find(params[:menu_id])
#menu_recipe = #menu.add_recipe(menu.id)
if #menu_recipe.save
redirect_to {admin_menu_recipe_url}
end
end
end
end
end
im i doing it right? if anything is needed please just ask thanks in advance
My guess is it's how you are getting the recipe_id. I would maybe debug the params and see what the actual values are.
You may need to do something like this:
params[:menu_recipe][recipe_id]