Im a rails noob, so bear with me.
I have the following in new.html.erb:
<h1>New page</h1>
<%= render 'pages/form' %>
<% if #page != 1 %>
<%= button_to 'New Page', pages_path %>
<%= button_to 'Done!', :action=> 'generate' %>
<% end %>
my controller looks like this
def generate
#presentation = current_presentation
respond_to do |format|
format.json { render json: #presentation.pages}
format.html {render :text => "html"}
end
end
I want the response to be JSON, but the code goes to format.html.
How do I instruct the button_to that my requested response is JSON?
Not sure if just one of them or both, but try :remote => true and data-type:
<%= button_to "Create", :action => "create", :remote => true, :form => { "data-type" => "json" } %>
Using a path helper to build the path worked for me. eg.
<%= button_to "Create Widgit", widgits_path(format: 'json'), remote: true %>
Related
I would like to pass a parameter with this link_to helper. How do I do that?
<%= link_to ('/my_controller/my_action') do %>
<div>haha</div>
<% end %>
The original code I had used the standard text link:
<%= link_to("link text", {:controller => 'my_controller', :action => 'my_action', :id => my_id}) %>
Just like in your second example:
<%= link_to({:controller => 'my_controller', :action => 'my_action', :id => my_id}) do %>
My text goes here
<% end %>
If you have a path helper for this (i.e. if it's something like PostsController's show action) then you could do:
<%= link_to post_path(my_id) do %>
My text goes here
<% end %>
From my understanding you want to pass options to the link_to helper when using a block.
From the documentation at http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
This is possible with the following format
link_to(options = {}, html_options = {}) do
# name
end
To give you an example and using the code you provided:
<%= link_to({:controller => 'my_controller', :action => 'my_action', :id => my_id}) do %>
<div>haha</div>
<% end %>
Hello I'm new to rails 4
I am working on project where we can post and rate it. I have used activerecord reputation gem. I have been following the http://railscasts.com/episodes/364-active-record-reputation-system video.
I am stuck at the routing point. When I click on upvote or downvote it shows me error.
my routes.rb file has
resources :posts do
resources :comments, :only => [:create]
member { post :vote }
end
get "posts/create"
get "posts/destroy"
get "posts/new"
get "posts/index"
get "posts/show"
get "posts/edit"
get "posts/update"
_post.html.erb
<h4 class="timeline-title"><%= link_to_unless_current post.title, post %></h4>
<p> Created : <%= post.created_at.strftime("%d/%m/%Y") %> by <%= post.postedby %>
</p>
<% if current_cubestudent.email == post.postedby %>
<p><%= link_to 'Edit', edit_post_path(#post) %>
<%= link_to 'Destroy', posts_path, method: :delete, data: { confirm: 'Are you sure?' } %>
<% end %>
<%= simple_format post.body , :class => "timeline-body"%>
<%= pluralize post.reputation_for( :votes).to_i, "vote" %>
<% if current_cubestudent && !current_cubestudent.voted_for?(post) %>
<%= link_to "up", vote_post_path(post, type: "up"), method: "post" %>
<%= link_to "down", vote_post_path(post, type: "down"), method: "post" %>
<% end %>
my post#show is
<%= stylesheet_link_tag "application",:media =>"screen" %>
<p id="notice"><%= notice %></p>
<p id="alert"><%= alert %></p>
<%= render :partial => #post %>
<%= link_to 'Back', posts_path %>
<h2 id="timeline">Comments</h2>
<div>
<%= render :partial => #post.comments %>
</div>
<div class="container">
<%= form_for [#post, Comment.new] do |f| %>
<div style="padding-bottom:0">
<%= f.text_area :body , :placeholder => "Write your comment"%>
<%= f.submit "Add comment", :class => "btn btn-info" %>
</div>
<% end %>
</div>
posts controller is
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def create
#post = Post.new(post_params)
#post.postedby = current_cubestudent.email
#post.postedbyid = current_cubestudent.id
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render action: 'show', status: :created, location: #post }
else
format.html { render action: 'new' }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def destroy
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
def new
#post = Post.new
end
def index
#posts = Post.find_with_reputation(:votes, :all, order: "votes desc")
end
def show
#post = Post.find(params[:id])
end
def edit
end
def update
respond_to do |format|
if #post.update(post_params)
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
def vote
value = params[:type] == "up" ? 1 : -1
#post = Post.find(params[:id])
#post.add_or_update_evaluation(:votes, value, current_cubestudent)
redirect_to :back, notice: "Thank you for voting"
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
#post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:title, :body, :subject)
end
end
after rake routes | grep post
C:\Sites\project>rake routes | grep post
post_comments POST /posts/:post_id/comments(.:form comments#create
vote_post POST /posts/:id/vote(.:format) posts#vote
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PATCH /posts/:id(.:format) posts#update
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
posts_create GET /posts/create(.:format) posts#create
posts_destroy GET /posts/destroy(.:format) posts#destroy
posts_new GET /posts/new(.:format) posts#new
posts_index GET /posts/index(.:format) posts#index
posts_show GET /posts/show(.:format) posts#show
posts_edit GET /posts/edit(.:format) posts#edit
posts_update GET /posts/update(.:format) posts#update
Can someone help me on it....??
Your main problem is in this code
<%= link_to "up", vote_post_path(post, type: "up"), method: "post" %>
you would like to send "post" request but in fact you send default ("get") request.
I can suppose that link_to accepts only symbols for method (you pass string). So try this
<%= link_to "up", vote_post_path(post, type: "up"), method: :post %>
Another source of the problem can be wrong routes. If code above does not help you run in console rake routes | grep post and add output to the question.
I try a bit of ajax first time but did not get success, i want to render a partial on radio button select using ajax, here is my code :
My script.js:
$(document).ready(function(){
$.ajax({
url : "/income_vouchers/income_voucher_partial?$('form input[type=radio]:checked').val()="+$('form input[type=radio]:checked').val(),
type: "GET",
data: {
type: $('form input[type=radio]:checked').val()
}
});
});
income_voucher.js.erb
$("#payment_mode").append('
<% if params[:type]== 'cheque' %>
<%= escape_javascript render :partial => "cheque" %>
<% elsif params[:type]=='card' %>
<%= escape_javascript render :partial => "card" %>
<% elsif params[:type]=='ibank'%>
<%= escape_javascript render :partial => "ibank" %>
<% else params[:type] == 'cash' %>
<% end %>
');
My from:
<script type="text/javascript" src="/javascripts/voucher.js"></script>
<%= form_for(#income_voucher) do |f| %>
<%= render 'shared/form_error', :object => #income_voucher %>
<div >
<%= radio_button_tag :transaction_type,'cash', :checked => true %>
<%= f.label :transaction_type, "Cash", :value => "cash" %>
<%= radio_button_tag :transaction_type,'cheque' %>
<%= f.label :transaction_type, "Cheque", :value => "cheque" %>
<%= radio_button_tag :transaction_type,'card'%>
<%= f.label :transaction_type, "Card", :value => "card" %>
<%= radio_button_tag :transaction_type,'ibank'%>
<%= f.label :transaction_type, "Internet Banking", :value => "ibank" %>
</div>
<div id = "payment_mode">
<% if params[:type]== "cheque" %>
<%= render :partial => "cheque", :f => f %>
<% elsif params[:type]=='card' %>
<%= render :partial => "card", :f => f %>
<% elseif params[:type] == 'ibank'%>
<%= render :partial => "ibank", :f => f %>
<% else params[:type] == 'cash' %>
<% end %>
</div>
<%= f.submit %>
<% end %>
and here is my controller method:
class IncomeVouchersController < ApplicationController
def new
#income_voucher = IncomeVoucher.new
#invoices = current_company.invoices
#income_voucher.build_payment_mode
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #income_voucher }
end
end
def create
#income_voucher = IncomeVoucher.new(params[:income_voucher])
transaction_type = params[:transaction_type]
payment_mode = nil
if transaction_type == 'cheque'
payment = ChequePayment.new(params[:cheque_payment])
payment.amount = #income_voucher.amount
elsif transaction_type == 'card'
payment = CardPayment.new(params[:card_payment])
payment.amount = #income_voucher.amount
elsif transaction_type == 'ibank'
payment = InternetBankingPayment.new(params[:internet_banking_payment])
payment.amount = #income_voucher.amount
else
payment = CashPayment.new
payment.amount = #income_voucher.amount
end
payment_mode = PaymentMode.new
payment_mode.transactionable = payment
#income_voucher.payment_mode = payment_mode
respond_to do |format|
if #income_voucher.save
format.html { redirect_to(#income_voucher, :notice => 'Income voucher was successfully created.') }
format.xml { render :xml => #income_voucher, :status => :created, :location => #income_voucher }
else
format.html { render :action => "new" }
format.xml { render :xml => #income_voucher.errors, :status => :unprocessable_entity }
end
end
def income_voucher_partial
#payment_mode = PaymentMode.new(params[:payment_mode])
end
end
i can see my view form but when select a radio button nothing is rende. Any help would be appreciated
First of all: choose the method - or you using remote form, or ajax submit. If your want that user choose radio button AND click submit to render use in .html.erb:
form_for(#income_voucher, :remote => true)
remove javascript ajax and change param name in .js.erb to :transaction_type
If you want that user choosse radio button and immidiately render move javascript ajax to radio button change event handler like this
$(your_element).change(function(){
$.ajax(){
url : "/income_vouchers/income_voucher_partial",
data: {
type: $('form input[type=radio]:checked').val()
}
}
});
and remove params setting from directly url - set params in 'data:'
in my js.erb file i did this
$(".gradeU").remove();
$("#abcd").after(
'<%= escape_javascript render :partial => params[:payment] unless params[:payment] == 'cash' %>'
);
and in my script :
$(document).ready(function(){
$("#check").click(function(){
var payment = $('form input[type= radio]:checked').val()
console.debug(payment);
$.ajax({
type: 'GET',
url : "/income_vouchers/income_voucher_partial?payment="+payment,
});
});
});
and i did not render same code in form, thanks
i have a nested form model
<%= simple_form_for(#product, :html => { :multipart => true }) do |f| %>
<%= f.input :name %>
#... and some other
<%= f.simple_fields_for :productgroups do |builder| %>
<%= render 'form_productgroup', { :f => builder } %>
<% end %>
<% end %>
## partial-level-1: form_productgroup
<%= f.input :extrapercentage %>
#... and some other
<%= f.simple_fields_for :productmaterials do |builder| %>
<%= render 'form_productmaterial', { :f => builder } %>
<% end %>
## partial-level-2: form_productmaterial
<%= f.input :price %>
#... and some other
=> everything fine serverside, but i need to add records via ajax because each productgroup or productmaterial belongs to a specific type
now the question:
how to create a controller action which returns the new material form?
This code returns an error that f is not existing:
def new_productgroup
#product = Product.find(params[:id])
#productgroup = Productgroup.new(:product_id => #product.id, :materialgroup_id => params[:materialgroup_id])
render "form_productgroup", { :f => ???? }
end
please help me!
Here is my simple ajax code.
The request is made, I get the response but my view does not get rendered with new data. I get a new page with new html that I asked to render instead being rendered inside current page.
controller -
def list
#users = User.find(:all)
end
def show
respond_to do |format|
format.html { render :partial => "ajaxshow" }
format.js
end
end
view -
<% #users.each do |c| %>
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id, :remote => true } %>
<% end %>
partial -
# cat _ajaxshow.html.erb
<div align="left" id="user_ajax">
<table width="1000px">
<tr><th>User ID</th><th>First</th><th>Last</th><th>ID</th><th>Email</th></tr>
</table>
log -
Started GET "/users/show?remote=true&user_id=someuser" for 10.10.10.10 at 2012-04-17 04:01:09 -0400
Processing by UsersController#show as HTML
Parameters: {"remote"=>"true", "user_id"=>"someuser"}
Rendered users/_ajaxshow.html.erb (0.3ms)
Completed 200 OK in 2ms (Views: 1.3ms | ActiveRecord: 0.0ms)
Your link_to will not trigger the ajax call
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id, :remote => true } %>
First change the above code
<%= link_to c.user_id, {:action => :show, :user_id => c.user_id }, { :remote => true, :method => :get } %>
You need to have a .js.erb file for the User controller action which will be called through the format.js call.
In show.js.erb use
$('#some_div_id').html($('<%= render :partial => "ajaxshow" %>'))
Anyhow the purpose of your action seems obscure to me.