Rails Polymorphic - controller & views - ruby-on-rails

Hi I'm trying to create an event depending on the eventable type. the eventable type is either group or shop.
Writing my code, I'm currently sure that their is a better way create my routes and controller (still a rails newbie)
Is there a way to create only one new and create method pass in the eventable type ?
Models:
class Event < ActiveRecord::Base
belongs_to :eventable, polymorphic: true
class Group < ActiveRecord::Base
has_many :events, as: :eventable
class Shop < ActiveRecord::Base
has_many :events, as: :eventable
Routes:
resources :events do
collection do
get :new_national_event
get :new_local_event
post :create_national_event
post :create_local_event
end
do
event-controller:
def index
#search = Search.new(params[:search])
#shop = find_user_shop(#search.shop_id)
#group = #shop.group
#shop_events = #shop.events
#group_events = #group.events
end
def new_national_event
#user = current_user
#event = #user.group.events.new
end
def new_local_event
#shop = find_user_shop(#search.shop_id)
#event = #shop.events.new
end
def create_national_event
user = current_user
#event = user.group.events
if #event.save!
flash.now[:notice] = "Votre événement national a bien été enregistré"
render :index
else
flash.now[:error] = "Erreur lors de l'enregistrement du événement national"
render :new
end
end
def create_local_event
user = current_user
#event = user.group.shop.events
if #event.save!
flash.now[:notice] = "Votre événement local a bien été enregistré"
render :index
else
flash.now[:error] = "Erreur lors de l'enregistrement du événement local"
render :new
end
end
views:
index.html.slim
= link_to new_national_event_events_path
= link_to new_local_event_events_path
new_national_event_events_path.html.slim
= form_for #event, :url => create_national_event_events_path, :method => :post do |f|
div class="field"
= f.text_field :title, :required => true
div class="field"
= f.text_field :threshold, :required => true
div class="form-actions"
=f.submit "Create", class: "btn blue"

If it is just the routing you are concerned with, and not the number of actions, you can use constraints to allow a single path variable send the request to one of a multiple number of actions, this can be useful in some cases where you may want to have multiple buttons to multiple actions all reading from a single form, or if you just want to simplify your routes variable naming.
use the commit_param_routing gem and in your routes file you can write something like:
resources :events do
collection do
post :save, constraints: CommitParamRouting.new(EventController::CREATENATIONAL), action: :create_national_event
post :save, constraints: CommitParamRouting.new(EventController::CREATELOCAL), action: :create_local_event
end
end
add the constants to your controller:
class EventController
CREATENATIONAL = "create national"
CREATELOCAL = "create local"
.....
end
and then all that is left is to add them to your view file submit buttons:
div class="form-actions"
.row
.col-xs-2
=f.submit EventController::CREATENATIONAL
.col-xs-2
=f.submit EventController::CREATELOCAL
sorry for if its not quite what you were looking for or unclear, my first answer!

Related

create an instance of a model by clicking a button

I am pretty new to Ruby and I am working on a hangman game .
What I am trying to do is create a new game when the user simply click on a button and I want that "click" to redirect to the show of that game.
Here are my models :
class Game < ApplicationRecord
has_many :guesses
end
class Guess < ApplicationRecord
belongs_to :game
end
Here are my controllers :
class GamesController < ApplicationController
skip_before_action :authenticate_user!
def index
#games = Game.all
end
def create
#game = Game.new(game_params)
#game.save!
redirect_to game_path(#game)
end
def show
#game = Game.new
#game = Game.last
end
def destroy
#game = Game.find(params[:id])
#game.destroy
redirect_to home_path
end
private
words =[
"spokesperson", "firefighter", "headquarters", "confession", "difficulty", "attachment", "mechanical",
"accumulation", "hypothesis", "systematic", "attraction", "distribute", "dependence", "environment",
"jurisdiction", "demonstrator", "constitution", "constraint", "consumption", "presidency", "incredible",
"miscarriage", "foundation", "photography", "constituency", "experienced", "background", "obligation",
"diplomatic", "discrimination", "entertainment", "grandmother", "girlfriend", "conversation", "convulsion",
"constellation", "leadership", "insistence", "projection", "transparent", "researcher", "reasonable","continental",
"excavation", "opposition", "interactive", "pedestrian", "announcement", "charismatic", "strikebreaker",
"resolution", "professional", "commemorate", "disability", "collection", "cooperation", "embarrassment",
"contradiction", "unpleasant", "retirement", "conscience", "satisfaction", "acquaintance", "expression",
"difference", "unfortunate", "accountant", "information", "fastidious", "conglomerate", "shareholder",
"accessible", "advertising", "battlefield", "laboratory", "manufacturer", "acquisition", "operational",
"expenditure", "fashionable", "allocation", "complication", "censorship", "population", "withdrawal",
"sensitivity", "exaggerate", "transmission", "philosophy", "memorandum", "superintendent", "responsibility",
"extraterrestrial", "hypothesize", "ghostwriter", "representative", "rehabilitation", "disappointment",
"understanding", "supplementary", "preoccupation"
]
#word_to_guess = words.sample
#health_bar = 5
#game_status = "Game not started yet"
def game_params
params.require(:game).permit(#word_to_guess, #health_bar, #game_status)
end
end
Here is what I have been trying to do
<%= link_to "nouvelle partie", game_path(game), method: :create %>
but the errors message is :
"undefined local variable or method `game' for #ActionView::Base:0x0000000000d4d0"
POST method won't work with link_to. Try using the to button_to instead of link_to like this:
<%= button_to "nouvelle partie", game_path(game), method: :post %>
I think the bug is due to the variable game not being passed to partial. You have to pass it on like this:
<%= render "game", game: #game %>
And you don't have to pass variables in game_params. You only need to set them in the show method where you will be redirected from the create method. Also, you don't set the current game like this Game.last, you just take id which is contained in the url.
def create
#game = Game.new
#game.save!
redirect_to game_path(#game)
end
def show
#game = Game.find(params[:id])
#word_to_guess = words.sample
#health_bar = 5
#game_status = "Game not started yet"
end
have you tried?
<%= link_to "nouvelle partie", game_path(#game), method: :create %>

Params issue with nested attributes

I'm having trouble with what I feel should be a simple issue. I'm trying to create a basic match score reporting app and I'm trying to create a match and the match players simultaneously.
My models:
class Match < ApplicationRecord
has_many :match_players
accepts_nested_attributes_for :match_players
end
class MatchPlayer < ApplicationRecord
belongs_to :player
belongs_to :match
end
My form:
.container
%h1 Log a completed match
= simple_form_for #match do |f|
= f.input :played_at, html5: true
= f.simple_fields_for :match_player do |mp|
= mp.input :player_id, collection: Player.all, label_method: lambda { |player| player.first_name + " " + player.last_name }
= f.submit "Submit Match Score"
My controller action and params:
def create
#match = Match.new(match_params)
if #match.save
player = MatchPlayer.create(player: current_player, match: #match)
opponent = MatchPlayer.create(player: Player.find(match_params[:match_player_attributes][:player_id], match: #match))
else
render :new
end
end
private
def match_params
params.require(:match).permit(:played_at, match_player_attributes: [:player_id])
end
Right now I'm getting a found unpermitted parameter: :match_player issue. If I change match_player_attributes to match_player in my params then I get unknown attribute 'match_player' for Match. The error is occurring on the first line of the create action (#match = Match.new(match_params))
Any help would be appreciated!
Edit following suggestions:
Controller:
def new
#match = Match.new
#match.match_players.build
end
def create
#match = Match.new(match_params)
if #match.save!
player = MatchPlayer.create(player: current_player, match: #match)
opponent = Player.find(match_params[:match_players_attributes]["0"][:player_id])
opponent_match_player = MatchPlayer.create(player: opponent, match: #match)
redirect_to(root_path, notice: "Success!")
else
render :new
end
end
private
def match_params
params.require(:match).permit(:played_at, match_players_attributes: [:player_id])
end
Form:
= simple_form_for #match do |f|
= f.input :played_at, html5: true
= f.simple_fields_for :match_players do |mp|
= mp.input :player_id, collection: Player.all, label_method: lambda { |player| player.first_name + " " + player.last_name }
= f.submit "Submit Match Score"
Now it's creating 3 match_players, one for the current_player and 2 of the opponent. What's going on?
Looks like the problem in the simple typo,
Try to change:
= f.simple_fields_for :match_player do |mp|
to
= f.simple_fields_for :match_players do |mp|
Also
def match_params
params.require(:match).permit(:played_at, match_player_attributes: [:player_id])
end
to
def match_params
params.require(:match).permit(:played_at, match_players_attributes: [:player_id])
end
Here is wiki with examples
UPD:
From wiki I shared with, you can find this point:
accepts_nested_attributes_for - an ActiveRecord class method that goes
in your model code - it lets you create and update child objects
through the associated parent. An in depth explanation is available in
the ActiveRecord documentation.
It means that you don't need to create opponent manually
opponent = Player.find(match_params[:match_players_attributes]["0"][:player_id])
opponent_match_player = MatchPlayer.create(player: opponent, match: #match)
Because when you send your params with nested attributes:
match_players_attributes: [:player_id] inside of match creation process match_player will be created automatically
I can see in your model, you have:
has_many :match_players
hence, in your controller and in your form, you must use match_players (plural not singular)
Thus, in your controller, you will have:
def match_params
params.require(:match).permit(:played_at, match_players_attributes: [:id, :player_id])
end
And, in your form:
...
= f.simple_fields_for :match_players do |mp|
...
Notice the last s of match_player in form and in controller.

NoMethodError in Lines#show

UPDATE: The answer bellow is correct. Just wanted to update what I did to solve the problem.
First I had to delete all my previous lines in the rails console.
Then I used the bye bug gem in my lines controller at the bottom of the create method to discover where the next bug occurred. I created a test line that I needed to delete again. so I ran
Line.last.delete in console.
This is the way my lines controller create method looks now (working no bugs)
def create
if user_signed_in?
#line = Line.create(line_params)
if #line
if params[:line][:previous_line_id].empty?
#line.story = Story.create
#line.save
else
#line.story = #line.previous_line.story
#line.save
end
redirect_to line_path(#line)
else
flash[:error] = #line.errors
redirect_to line_path(Line.find(params[:line][:previous_line_id]))
end
else
Finally I ran #Lines.each { |line| line.update.attribute(:story_id: 3)}
This gave the necessary association between lines and story.
ORIGINAL POST BELLOW.
I'm getting this error in my rails app. I think that when I create a new line or start a story, it doesn't automatically add it to a story object. I've listed my show.html.erb file as well as my lines controller.rb file.
What am I missing? How do I get the controller to add data to the story object correctly?
Thanks!
I added a few lines of code to my lines controller:
class LinesController < ApplicationController
def new
params[:previous_line_id].nil? ? #line = Line.new : #line = Line.find(params[:previous_line_id]).next_lines.create
#lines = #line.collect_lines
#ajax = true if params[:ajax]
render :layout => false if params[:ajax]
if #line.previous_line
#line.update_attribute(:story_id, #line.previous_line.story.id)
else
story = Story.create
#line.story = story
#line.save
end
end
def create
if user_signed_in?
#line = Line.create(line_params)
if #line
redirect_to line_path(#line)
else
flash[:error] = #line.errors
redirect_to line_path(Line.find(params[:line][:previous_line_id]))
end
else
flash[:error] = "Please sign in or register before creating a line!"
unless params[:line][:previous_line_id].empty?
redirect_to line_path(Line.find(params[:line][:previous_line_id]))
else
redirect_to root_path
end
end
end
# params[:id] should correspond to the first line of the story.
# if params[:deeper_line_id] is not nil, that means that they want to render up to the nested line id
def show
#lines = Line.find(params[:id]).collect_lines
#next_lines = #lines.last.next_lines.ranked
#lines.last.update_attribute(:score, #lines.last.score + 1)
end
def select_next
#line = Line.find(params[:id])
#line.update_attribute(:score, #line.score + 1)
#lines = [#line]
#next_lines = #line.next_lines.ranked
render :layout => false
end
def send_invite
if user_signed_in?
UserInvite.send_invite_email(current_user,Line.find(params[:id]), params[:email]).deliver
flash[:notice] = "Your invite was sent!"
else
flash[:error] = "Please sign in"
end
redirect_to Line.find(params[:id])
end
private
def line_params
params.require(:line).permit(:text, :previous_line_id, :user_id)
end
end
I added these lines to the controller pictured above
if #line.previous_line
#line.update_attribute(:story_id, #line.previous_line.story.id)
else
story = Story.create
#line.story = story
#line.save
end
Here is my show.html.erb file
<div class="row">
<div class="col-lg-2">
</div>
<div class="box-container col-lg-7 ">
<div id="story" class="box">
<% #lines.each do |line| %>
<span class="story-line" data-id="<%=line.id%>"><%= link_to line.text, '#', :class=>"story-line" %></span>
<% end %>
</div>
<div id="next-steps">
<%= render 'next_steps' %>
</div>
<span style="font-size:.9em; margin-bottom:15px; display:block;">*If the links don't work, try refreshing.</span>
</div>
<div class="col-lg-2" style="padding-right:25px;">
<%= render 'invite' %>
Your Fellow Collaborators: <br />
<div class="collaborators">
<% #lines.last.story.collaborators.uniq.each do |collaborator| %>
<%= link_to profile_path(:id => collaborator.id) do %>
<%= image_tag collaborator.profile_image_uri, :class => "prof-icon" %>
<% end %>
<% end %>
</div>
Story model
class Story < ActiveRecord::Base
has_many :lines
has_and_belongs_to_many :collaborators, :class_name => "User", :join_table => "collaborators_stories", :association_foreign_key => :collaborator_id
def first_line
self.lines.first_lines.first_lines.first
end
end
Here is my lines.rb file
class Line < ActiveRecord::Base
scope :first_lines, -> { where previous_line_id: nil}
scope :ranked, -> { order("score + depth DESC")}
belongs_to :user
belongs_to :story
belongs_to :previous_line, :class_name => "Line", :foreign_key => "previous_line_id"
has_many :next_lines, :class_name => "Line", :foreign_key => "previous_line_id"
validates_presence_of :text
after_create :update_depths
def update_depths
line = self.previous_line
while !line.nil?
line.update_attribute(:depth, line.depth + 1)
line = line.previous_line
end
end
def first_line
line = self
while !line.previous_line.nil?
line = line.previous_line
end
line
end
def collect_lines
line = self
lines = [self]
while !line.previous_line.nil?
lines.unshift(line.previous_line)
line = line.previous_line
end
lines
end
end
Problem is orphaned lines in your database. Look for them and associate it to a story, or delete it:
How to find orphaned records:
http://antonzolotov.com/2013/01/26/how-to-find-and-delete-orphaned-records-with-ruby-on-rails.html
Then review the create method to ensure a line should be part of a story:
#short example review activerecord relations
#story = Story.find(params[:story_id])
story.lines.create(line_params)
That should work.
EDIT:
def self.find_orphan_ids
Lines.where([ "user_id NOT IN (?) OR story_id NOT IN (?)", User.pluck("id"), Story.pluck("id") ]).destroy_all
end

Rails 4 Cannot access hash in nested form (undefined method `[]' for nil:NilClass)

I've build quite complex form which creates one prescription with many realtions. I am using this syntax in view:
- provide(:title, 'Create prescription')
%h1 Add medicines to prescription
.row
.span6.offset3
= form_for #prescription do |f|
= render 'shared/error_prescription_messages'
%p
= f.hidden_field :patient_id, :value => params[:patient_id]
= f.hidden_field :user_id, :value => current_user.id
= f.fields_for :relations do |builder|
= render 'child_form', :f => builder
%p= f.submit "Submit"
chlid_form is quite simple :
- it=f.options[:child_index].to_i
- n= it.to_s
%h2
= "Medicine ##{it+1}"
= f.hidden_field :medicine_id, :id => "my_medicine_id#{it}"
- if params[:prescription].nil? || params[:prescription][:relations_attributes][n.to_sym][:medicine_name].nil?
= f.autocomplete_field :medicine_name, autocomplete_medicine_name_relations_path, :id_element => "#my_medicine_id#{it}"
- else
= f.autocomplete_field :medicine_name, autocomplete_medicine_name_relations_path, :id_element => "#my_medicine_id#{it}", :value => params[:prescription][:relations_attributes][n.to_sym][:medicine_name]
= f.label :amount, "Amount of medicine boxes"
= f.number_field :amount, :value => 1
= f.label :daily
= f.number_field :daily, :value => 1
= f.label :period_in_days, "Duration of treatment (in days)"
= f.number_field :period_in_days, :value => 1
So as you can see I'm using f.options[:child_index] to get index of child (0,1,2...) cause I generate multiple items with this particular form. I then put it to variable it and sucessfully use it in :id_element => "#my_medicine_id#{it}" which works PERFECTLY fine (creates my_medicine_id0, my_medicine_id1 ....) Although it doesn't work in this line:
:value => params[:prescription][:relations_attributes][n.to_sym][:medicine_name]
where n is just n=it.to_s.
I though somethings wrong in controller but if I change this line to whatever
:value => params[:prescription][:relations_attributes]**[:'0']**[:medicine_name] or any other integer from 0 to 4 everything works great, but I NEED dynamic change in this one. So I got proof that it DOES work because it generates integer fine here "#my_medicine_id#{it}" but won't work in hash! And when I print the whole hash from params I get this:
{"patient_id"=>"7", "user_id"=>"1", "relations_attributes"=>{"0"=>{"medicine_id"=>"13490", "medicine_name"=>"Locacid 500 mcg/g (0,05%) (1 tuba 30 g)", "amount"=>"0", "daily"=>"1", "period_in_days"=>"1"}, "1"=>{"medicine_id"=>"", "medicine_name"=>"", "amount"=>"1", "daily"=>"1", "period_in_days"=>"1"}, "2"=>{"medicine_id"=>"", "medicine_name"=>"", "amount"=>"1", "daily"=>"1", "period_in_days"=>"1"}, "3"=>{"medicine_id"=>"", "medicine_name"=>"", "amount"=>"1", "daily"=>"1", "period_in_days"=>"1"}, "4"=>{"medicine_id"=>"", "medicine_name"=>"", "amount"=>"1", "daily"=>"1", "period_in_days"=>"1"}}}
so to get the values I need it's pretty obvious that
params[:prescription][:relations_attributes][SOME_KIND_OF_INETEGER][:medicine_name] should work, but doesn't.
Controller code:
class PrescriptionsController < ApplicationController
before_action :signed_in_user
before_action :doctor_user, only: [:new, :create]
before_action :pharmacist_user, only: [:update]
def new
#prescription =Prescription.new
5.times { #prescription.relations.build }
end
def create
#prescription = Prescription.new(new_prescription_params)
if #prescription.save
flash[:success] = "Prescription created."
redirect_to #prescription
else
5.times { #prescription.relations.build }
render 'new', :prescription => params[:prescription]
end
end
def show
#prescription = Prescription.find(params[:id])
#medicines = #prescription.medicines.paginate(page: params[:page], :per_page => 10)
end
def update
#prescription = Prescription.find(params[:id])
#patient = Patient.find(params[:patient_id])
if !prescription_expired?(#prescription)
#prescription.realized = 1
if #prescription.save
flash[:success] = "Prescription realized."
redirect_to #patient
else
redirect_to root_url
end
else
flash[:notice] = "Can't realize, prescription expired."
redirect_to #patient
end
end
private
def new_prescription_params
params.require(:prescription).
permit(:patient_id, :user_id, relations_attributes: [:medicine_id, :medicine_name, :amount, :daily, :period_in_days])
end
def doctor_user
redirect_to(root_url) unless current_user.function == "doctor"
end
def pharmacist_user
redirect_to(root_url) unless current_user.function == "pharmacist"
end
def prescription_expired?(presc)
presc.created_at < 1.month.ago
end
def signed_in_user
unless signed_in?
store_location
flash[:notice] = "Please log in."
redirect_to login_url
end
end
end
I run out of ideas so I ask you guys if anyone can help. Thanks.
There is no point in using params in your view since you already assigned those to your models. Also when you rendering your new action, those params doesn't exist as nothing has been send to the server yet. Just get rid of all the values from inputs.
Your partial should look like:
- it=f.options[:child_index].to_i
- n= it.to_s
%h2
= "Medicine ##{it+1}"
= f.hidden_field :medicine_id, :id => "my_medicine_id#{it}"
= f.autocomplete_field :medicine_name, autocomplete_medicine_name_relations_path
= f.label :amount, "Amount of medicine boxes"
= f.number_field :amount
= f.label :daily
= f.number_field :daily
= f.label :period_in_days, "Duration of treatment (in days)"
= f.number_field :period_in_days
If you want your fields to have default value, set default value inside your database.

Single model different view and CRUD functionality in RubyOnRails3

As a new to Ruby on rails, I stumble on a part of my app. I read the basics of RoR framework and know the 'convention over configuration' feature of rails MVC. I have two tables, one is apps_events and another is apps_events_attributes. The id of the first one is the foreign key of the second and in has many relationship. The app_events table has a field of foreign key attribute 'app_id', so selecting on a particular app I will be redirected to its events and attributes. There is also a field called 'is_standard' which actually distinguish the event type whether it's a Standard or Custom event.
Now I have to render those events and its attributes of a particular app in two different tab on the view layer with it's attributes using nested_form_for feature. User can toggle to Standard and Custom event through this tab click. Can anyone suggest me how will I achieve the same and can show me the ideal flow of this scenario (model name and checking part of 'is_standard', propagate the same in controller and render to the view)?
By the way, can I use different controller over the same model and if I do the same then is it capable of doing the same CRUD functionality for different Event and its attributes?
I have all it done alone and it is not very hard what I think at first, all trick is done by JQuery... and share the concept if somebody got same problem as me
My Models are
class AppsEvent < ActiveRecord::Base
belongs_to :app
has_many :apps_events_attributes, :foreign_key => 'apps_event_id',
:class_name => 'AppsEventsAttribute',
:dependent => :destroy
accepts_nested_attributes_for :apps_events_attributes,
:reject_if => lambda { |a| (a[:name].blank? && a[:description].blank?) },
:allow_destroy => true
validates_presence_of :description
validates_presence_of :name
validates_presence_of :code
validates_presence_of :apps_events_attributes, :message => "can't be empty"
end
and
class AppsEventsAttribute < ActiveRecord::Base
set_table_name :apps_events_attributes
belongs_to :apps_event, :foreign_key => 'apps_event_id'
attr_accessible :id, :apps_event_id, :name, :description, :attribute_type, :is_std, :created_at, :updated_at
def type
self.attribute_type
end
end
and My Controller is...
class AppsEventsController < ApplicationController
layout :layout_by_resource
before_filter :initialize_default_app
before_filter :check_permission
before_filter :load
def load
#app = current_user.find_app(params[:app_id])
#apps_events = AppsEvent.where(:app_id => #app.id)
#apps_event = AppsEvent.new
end
def index
#app = current_user.find_app(params[:app_id])
#default_app = App.default(current_user)
#apps_events = AppsEvent.where(:app_id => #app.id)
#apps_event_jsons = Hash.new
#apps_events.each do |app_event|
json = Hash.new
json['User_ID'] = 548741213
json['Session_ID'] = 2568639390
json['Action_Type'] = app_event.code
json['eventsData'] = {}
app_event.apps_events_attributes.each do |apps_event_attributes|
if (apps_event_attributes.attribute_type == 'Integer')
json['eventsData'][apps_event_attributes.name] = 1234
elsif (apps_event_attributes.attribute_type == 'Float')
json['eventsData'][apps_event_attributes.name] = 1234.23
else
json['eventsData'][apps_event_attributes.name] = 'abcd'
end
end
#apps_event_jsons[app_event.id] = json
end
end
def new
#apps_event = AppsEvent.new
#app = current_user.find_app(params[:app_id])
#apps_event.app_id = #app.id
#apps_event.apps_events_attributes.build
#action = 'create'
render 'edit'
end
def edit
#app = current_user.find_app(params[:app_id])
#apps_event = AppsEvent.find(params[:id])
#action = 'update'
end
def create
#apps_event = AppsEvent.new(params[:apps_event])
#show_custom_event = 'true'
#apps_event.name = #apps_event.name.strip
respond_to do |format|
if #apps_event.save
format.html {
redirect_to("/app/#{params[:apps_event][:app_id]}/apps_events",
:notice => "Successfully created #{#apps_event.name} custom definition.")
}
format.js {
flash[:notice] = 'Successfully created event.'
#apps_events = AppsEvent.where(:app_id => #app.id)
}
else
#app = current_user.find_app(params[:app_id])
if (#apps_event.apps_events_attributes == nil || #apps_event.apps_events_attributes.size <= 0)
#apps_event.apps_events_attributes.build
end
#apps_event.populate_code
#action = 'create'
format.html {
redirect_to("/app/#{params[:apps_event][:app_id]}/apps_events",
:alert => "Error in creating #{#apps_event.name} custom definition.")
}
format.js
end
end
end
def update
#apps_event = AppsEvent.find(params[:apps_event][:id])
params[:apps_event][:name] = params[:apps_event][:name].strip
respond_to do |format|
if #apps_event.update_attributes(params[:apps_event])
format.html {
if(#apps_event.is_std == 'y')
redirect_to("/app/#{params[:apps_event][:app_id]}/apps_events",
:notice => "Successfully updated #{#apps_event.name} standard definition.")
else
redirect_to("/app/#{params[:apps_event][:app_id]}/apps_events",
:notice => "Successfully updated #{#apps_event.name} custom definition.")
end
}
format.js {
flash[:notice] = 'Successfully updated event.'
#apps_events = AppsEvent.where(:app_id => #app.id)
render :nothing => true
}
else
#app = current_user.find_app(params[:app_id])
if (#apps_event.apps_events_attributes == nil || #apps_event.apps_events_attributes.size <= 0)
#apps_event.apps_events_attributes.build
end
#apps_event.populate_code
#action = "update"
format.html {
if(#apps_event.is_std == 'y')
redirect_to("/app/#{params[:apps_event][:app_id]}/apps_events",
:alert => "Error in updating #{#apps_event.name} standard definition.")
else
redirect_to("/app/#{params[:apps_event][:app_id]}/apps_events",
:alert => "Error in updating #{#apps_event.name} custom definition.")
end
}
format.js
end
end
end
def delete
if AppsEvent.delete(params[:id])
redirect_to "/app/#{params[:app_id]}/apps_events", :notice => "Successfully deleted #{#apps_event.name} custom definition."
else
redirect_to "/app/#{params[:app_id]}/apps_events",
:alert => "Error in deleting #{#apps_event.name} custom definition."
end
end
end
and I have 5 view files which are index.html.erb, edit.js.erb, _form_custom.html.erb, _form_standard.html.erb and _events.html.erb beside that have also a helper file for update, create and delete using ajax call by setting remote => true. In index file I am doing partial rendering all events(_events.html.erb) and here I done the trick :P
My _events.html.erb
<% for apps_event in #apps_events %>
<% if (apps_event.is_std == 'y') %>
<div class="standardEvent showStandard">
<ul>
<li class="column_1"><span style="font-weight: bold;"><%= apps_event.name %></span></li>
<li class="column_2"><span><%= apps_event.code %></span></li>
<li class="column_3"><span><%= apps_event.description %></span></li>
<li class="column_4">
<%= link_to edit_apps_event(apps_event) %>
</li>
<li class="column_5">
</li>
</ul>
</div>
<% else %>
<div class="customEvent showCustom" style="display:none">
<ul>
<li class="column_1"><span style="font-weight: bold;"><%= apps_event.name %></span></li>
<li class="column_2"><span><%= apps_event.code %></span></li>
<li class="column_3"><span><%= apps_event.description %></span></li>
<li class="column_4">
<%= link_to edit_apps_event(apps_event) %>
</li>
<li class="column_5">
<%= remove_apps_event_prompt_link(apps_event) %>
</li>
</ul>
</div>
<% end %>
<div class="clrBoth"></div>
<% end %>
now you can figure out the left part mean -- JQuery part to hide or show a div.

Resources