I'm working on a RoR backend for a big mobile app, currently with the admin panel.
I have two models: Activity and Deal, joined by HMT ActivitiesDeal. The join is tested both ways in rails console and works like a charm.
Activity is the model the app is built around, so admins need to be able to add deals to activity from the "Edit activity" form in some intuitive way.
I tried this for creating activities_deal:
<%=select("deal", #deal_id, Deal.all.collect {|d| [d.title, d.id]}, {})%>
<%= link_to "Add", link_activity_deal_path(activity_id: #activity.id, deal_id: #deal_id), method:'post' %>
But it doesn't work as I thought. Any ideas on how to send the correct deal_id to link_activity_deal_path? This seems like a problem that has been solved many times, but I can' find anything that fits.
ActivitiesDealsController:
class ActivitiesDealsController < ApplicationController
def create
#activity = Activity.find(params[:activity_id])
render file: 'public/404.html' and return unless #activity && Deal.find(params[:deal_id])
#activity_deal = ActivitiesDeal.new
#activity_deal.activity_id = params[:activity_id]
#activity_deal.deal_id = params[:deal_id]
if #activity_deal.save
redirect_to proc {activity_url #activity}
end
render file: 'public/500.html'
end
def destroy
p params
#activity = Activity.find(params[:activity_id])
render file: 'public/404.html' and return unless #activity
#activity_deal = ActivitiesDeal.where("activity_id == ? AND deal_id == ?", params[:activity_id], params[:deal_id])
render file: 'public/404.html' and return unless #activity_deal
ActivitiesDeal.destroy(#activity_deal)
redirect_to proc {activity_url #activity}
end
end
Fixed the problem by making a form_for outside of the edit page.
If anyone needs the code:
<%= form_for #activity, as: :deal, :url => link_activity_deal_path(activity_id: #activity.id), method:'post' do |f|%>
<%= f.collection_select :id, #deals, :id, :title %>
<%= f.submit "Add Deal", class: "btn btn-primary" %>
Related
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/
This is my first ror app.
I have main page: home.html.erb
I have form there.
<%= form_for(#lead ,:html => {:class => 'check_form'}) do |f| %>
<%= f.text_field :phone, placeholder: 'phone' %>
<%= f.submit "Check car status", class: "btn btn-large btn-primary" %>
<% end %>
Backstory: a customer(I call him Lead can input his phone number and check status of his car which is being repaired now.)
Right now this view home.html.erbis served by static_pages_controller
class StaticPagesController < ApplicationController
def home
#lead = Lead.new()
end
def help
end
def about
end
def contact
end
end
I have also LeadsController
class LeadsController < ApplicationController
*some code*
def create
#lead = Lead.new(lead_params)
if #lead.save
#sign_in #lead
flash[:success] = "Request successfully created!"
redirect_to #lead
else
render 'new'
end
end
* some code
end
What I want to do when user inputs his phone number to find lead in database with the same phone number and show repair status to user.
So back to my problem:
I know how to find lead by phone like this Lead.find(params[:id])
But where to write this code? I need to find lead by phone and then print it to screen. How can I do this?
What I want to do when user inputs his phone number to find lead in
database with the same phone number and show repair status to user.
Currently your form serves the wrong purpose. This requires a form with GET request. I'll be doing it by declaring a custom route like below
get :check_lead_car_status, to: 'static_pages#check_lead_car_status', as: 'check_lead_car_status'
And in the static_pages#check_lead_car_status
def check_lead_car_status
#lead = Lead.find_by(phone: params[:phone]
end
And modify the existing form like below
<%= form_tag check_lead_car_status_path, :method => :get do %>
<%= text_field_tag :phone, placeholder: 'phone' %>
<%= submit_tag "Check car status", class: "btn btn-large btn-primary" %>
<% end %>
And a page check_lead_car_status.html.erb with the below code
The Status of the Car is: <%= #lead.status %>
youre redirecting to #lead which means should be the show path in the lead controller. which means you need to put that logic in a method called show in your Lead controller
then in your view (views/leads/show.html.erb) you can access that variable
edit:
if all youre trying to do is query by a different parameter, then you should look into the active record query interface. specifically section 1.1.5
Lead.find_by(phone: params[:phone])
I have a message model and a user model. my message belongs_to my user and user has_many messages.
I'm trying to allow a user to private message another user while on their public profile page (their show template). I have tried a number of attempts, but I ultimately run back into the issue of requiring an ID to be attr_accessible (which I heard is bad to do). Am I doing something wrong?
My message model, I have :user_id (which is the current user, aka a sending_from ID), :to_id, :content.
When I'm looking at a users profile page, on the show template I have
<%= form_for([current_user, #message]) do |f| %>
<%= f.hidden_field :to_id, :value => #user.id %>
<div class="field">
<%= f.text_area :content, placeholder: "Send a private message..." %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
In my user show action, I have
def show
#user = User.find(params[:id])
#microposts = #user.microposts.paginate(page: params[:page])
if user_signed_in?
#message = current_user.messages.build(params[:messages], to_id: #user.id)
end
end
when the form submits, it goes to my message create action
def create
#message = current_user.messages.build(params[:message])
redirect_to user_path(params[:message][:to_id])
end
However, I always get the error
`Can't mass-assign protected attributes: to_id`
It seems like I can fix it by making :to_id attr_accessible, however I have heard it is not very safe to do so. Am I doing something wrong? This issue has been killing me.
Any help would be appreciated. Thanks
Making to_id accessible is fine. But if you don't want that error just fix it like this:
def create
#message = current_user.messages.build
#message.to_id = params[:message][:to_id]
# manually assign whatever other params you need to
redirect_to user_path(params[:message][:to_id])
end
Mass assignment just means you can't use update_attributes, you can still use model.attribute=. The reason for doing it that way might be to add additional whitelisting parameters, such as:
def create
safe_params = params[:model].slice(:safe_attr1,:safe_attr2)
#model = Model.new(safe_params)
whitelist = ['some_safe_string','another_safe_string']
if whitelist.include?(params[:model][:dangerous])
#model.dangerous_attribute = params[:model][:dangerous]
end
#model.save
redirect_to #model
end
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]
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 %>