undefined method `will_save_change_to_address - ruby-on-rails-3

I am new to coding and a friend and I are making a website that has a map with markers. For some reason it's working when she pulls the master branch but when I pull origin master on GitHub I get errors and no markers. Does anyone know why it works on one devise but not on another? We have been constantly running into this issue.
product model
class Product < ApplicationRecord
belongs_to :user
has_many :bookings, dependent: :destroy
validates :name, presence: true
validates :category, presence: true
has_one_attached :photo
geocoded_by :address
after_validation :geocode, if: :will_save_change_to_address?
include PgSearch::Model
pg_search_scope :search_by_name_and_category,
against: [ :name, :category ],
using: {
tsearch: { prefix: true } # <-- now `superman batm` will return something!
}
end
product controller
def index
if params[:query].present?
#products = Product.search_by_name_and_category(params[:query])
else
#products = Product.all
#markers = #products.geocoded.map do |product|
{
lat: product.latitude,
lng: product.longitude
}
end
end
end
private
def product_params
params.require(:product).permit(:name, :category, :price, :description, :address)
end
view
<div class="card-product-container">
<div class="cards">
<% #products.each do |product| %>
<div class="card-product">
<%= link_to product_path(product.id) do %>
<img src="https://source.unsplash.com/random/?<%= product.name %>" />
<div class="card-product-footer">
<div style="text-decoration:none;">
<h2><%= product.name %></h2>
<p>Owner <%= product.user.first_name %></p>
</div>
<h2><%= product.price %></h2>
</div>
<% end %>
</div>
<% end %>
</div>
<div style="width: 100%; height: 600px;"
data-controller="map"
data-map-markers-value="<%= #markers.to_json %>"
data-map-api-key-value="<%= ENV['MAPBOX_API_KEY'] %>">
</div>
</div>
schema
create_table "products", force: :cascade do |t|
t.string "name"
t.string "category"
t.boolean "available"
t.string "image"
t.text "description"
t.integer "price"
t.bigint "user_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.float "latitude"
t.float "longitude"
t.index ["user_id"], name: "index_products_on_user_id"
end
map controller
import { Controller } from "#hotwired/stimulus"
export default class extends Controller {
static values = {
apiKey: String,
markers: Array
}
connect() {
mapboxgl.accessToken = this.apiKeyValue
this.map = new mapboxgl.Map({
container: this.element,
style: "mapbox://styles/mapbox/streets-v10"
});
this.#addMarkersToMap()
this.#fitMapToMarkers()
}
#fitMapToMarkers() {
const bounds = new mapboxgl.LngLatBounds()
this.markersValue.forEach(marker => bounds.extend([ marker.lng, marker.lat ]))
this.map.fitBounds(bounds, { padding: 70, maxZoom: 15, duration: 0 })
}
#addMarkersToMap() {
this.markersValue.forEach((marker) => {
new mapboxgl.Marker()
.setLngLat([ marker.lng, marker.lat ])
.addTo(this.map)
})
}
}

Method will_save_change_to_address? comes from the Rails method will_save_change_to_attribute? . You get an error, because your Product model is missing address attribute. Just create a migration adding this column to the products table.

Related

Rails 3 Formtastic form not rendering

Here is my form view code:
<div class="row">
<%= semantic_form_for #new_athlete_sport, :remote => true, :html => { :class => "new_sport", :"data-type" => 'json', :id => '' } do |f| %>
<%= f.label "Sport" %>
<%= f.select :sport_id, Sport.all.collect { |sp| [sp.name, sp.id] }, {}, { class: "chosen", id: "" } %>
<br />
<%= f.submit %>
<% end %>
</div>
For some reason the <form> tag isn't showing up in the DOM, but every other fields show up..
Seems the syntax in form_for has some problem.
Try remove "id" and move "data-type" from this
<%= semantic_form_for #new_athlete_sport, :remote => true,
:html => { :class => "new_sport", :"data-type" => 'json', :id => '' } do |f| %>
to this
<%= semantic_form_for #new_athlete_sport, :remote => true, :data=> {:type=> 'json'}, :html => { :class => "new_sport"} do |f| %>

Activeadmin and Formtastic: form not responding to :size

I am trying to format a form and the text fields respond to some methods, and not others.
I can do things like:
f.input :name, :input_html => { :maxlength => 10 }
f.input :name, :input_html => { :disabled => true }
But if I try to do any of the following, they do not work:
f.input :name, :input_html => { :size => 10 }
f.input :name, :input_html => { :class => 'autogrow' }
f.input :name, :input_html => { :rows => 10, :cols => 10 }
When I try using :size, for instance, the generated html shows that size=10, but is not reflected in the actual form.
These were more or less pulled right from the Formtastic documentation on Github, which the Activeadmin documentation refers to.
I am not sure if your question is solved or not.
However according to Formastic Official WIKI, your code should work:
Customize HTML attributes for any input using the :input_html option.
Typically this is used to disable the input, change the size of a text
field, change the rows in a textarea, or even to add a special class
to an input to attach special behavior like autogrow textareas:
<%= semantic_form_for #post do |f| %>
<%= f.inputs do %>
<%= f.input :title, :input_html => { :size => 10 } %>
<%= f.input :body, :input_html => { :class => 'autogrow', :rows => 10, :cols => 20, :maxlength => 10 } %>
<%= f.input :created_at, :input_html => { :disabled => true } %>
<%= f.input :updated_at, :input_html => { :readonly => true } %>
<% end %>
<%= f.actions %>
<% end %>
https://github.com/justinfrench/formtastic
if your code doesn't work , please check out the error logs, or put more debug info to your erb file, to see if you r rails is running under production mode.
i had the same problem. i wanted a nested form for edit with custom text field size.this worked for me.
form do |f|
f.inputs "Header" do
cf.input :name, :input_html => { :class => 'some_style', :rows => 2, :style => 'width:50%'}
end
f.actions
end
so basically u have to create your own class or just work with the :style.
For nested form u can use this code
form do |f|
f.inputs "Header" do
f.has_many :name,:allow_destroy => true,:new_record => true do |cf|
cf.input :first_name, :input_html => { :class => 'some_style', :rows => 2, :style => 'width:50%'}
end
end
f.actions
end

Problem with nested form sign-up process

After researching on SO, I found that I desire a sign-up process that goes:
User fills out form
User clicks 'Join'
User is created/logged in and redirected to fill out profile
Button clicked
User directed to profile
If I were to create a User and User's Profile in rails console it would look like this:
user = User.new
user.email = ""
user.password = ""
user.profile = Profile.new
user.profile.info = ""
user.profile.save
user.save
THE PROBLEM: I'm using a nested model form on the homepage to create the user and add that user's profile first/last name. What happens now is: The user clicks 'Join', they are redirected to /users, then redirected to /signup. That's where I'm stuck. It gives me the following error:
Action Controller: Exception caught
NoMethodError in ProfilesController#new
undefined method `profile=' for nil:NilClass
app/controllers/profiles_controller.rb:5:in `new'
I want /signup to be a form to fill in the profile but it's not working.
My code below...
Users#new.html.erb (homepage form):
<%= form_for(#user, :html => {:multipart => true, :id => 'homesign'}) do |f| %>
<%= f.hidden_field :id %>
<% if #user.errors.any? %>
<% end %>
<div>
<%= f.label :email %>
<%= f.text_field :email, :size => 38 %>
</div>
...
<%= f.fields_for :profile do |profile| %>
<%= profile.label :first_name %>
<%= profile.text_field :first_name, :size => 18 %>
...
<% end %>
<% end %>
Profiles#new.html.erb (signup form):
<%= form_for #profile, :html => { :multipart => true } do |f| %>
<table id="signupTable">
<tbody>
<tr>
<td class="label"><%= f.label :gender, "Gender:" %></td>
<td>
<fieldset>
<%= select(:gender, :gender_type, [['Female', 1], ['Male', 2], ['Rather not say', 3]], :class => 'optionText') %>
</fieldset>
</td>
</tr>
<tr>
<td class="label"><%= f.label :birthday, "Birthday:" %></td>
<td>
<fieldset>
<%= select_month(14, :prompt => 'Month', :field_name => 'Month', :id => 'Date.mon') %>
<%= select_day(32, :prompt => 'Day') %>
<%= select_year(0, {:prompt => "Year", :start_year => DateTime.now.year, :end_year => DateTime.now.year - 115}, {:field_name => 'Year', :id => 'Date.year'}) %>
</fieldset>
<% end %>
User.rb:
class User < ActiveRecord::Base
attr_accessor :password
has_one :profile, :dependent => :destroy
accepts_nested_attributes_for :profile
validates :email, :uniqueness => true,
:length => { :within => 5..50 },
:format => { :with => /^[^#][\w.-]+#[\w.-]+[.][a-z]{2,4}$/i }
validates :password, :confirmation => true,
:length => { :within => 4..20 },
:presence => true,
:if => :password_required?
end
Profile.rb:
class Profile < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end
UsersController:
class UsersController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]
def new
#user = User.new
#user.profile = Profile.new
if logged_in?
redirect_to current_user.profile
end
end
def index
#user = User.all
end
def create
#user = User.new(params[:user])
if #user.save
session[:user_id] = user.id
redirect_to new_user_profile_path(:user_id => #user), :notice => 'User successfully added.'
else
render :action => 'new'
end
end
end
ProfilesController:
class ProfilesController < ApplicationController
before_filter :authenticate, :only => [:edit, :update]
def new
#user.profile = Profile.new
end
def create
#profile = Profile.new(params[:profile])
if #profile.save
redirect_to profile_path(#profile), :notice => 'User successfully added.'
else
render :action => 'new'
end
end
def index
#profile = current_user.profile
end
end
SessionsController (create only):
class SessionsController < ApplicationController
def create
if user = User.authenticate(params[:email], params[:password])
session[:user_id] = user.id
redirect_to user.profile, :notice => "Logged in successfully"
else
flash.now[:alert] = "Invalid login/password. Try again!"
render :action => 'new'
end
end
end
Routes.rb:
match "/signup" => "profiles#new", :as => "signup"
post "/profiles/new" => "profiles#create"
match "skip/signup", :to => "info#signupskip"
match "skip/profiles/new", :to => "profiles#newskip"
get "/profiles/:id" => "profiles#show", :as => "profile"
get "profiles/new"
root :to => "users#new"

How to retrieve data via ajax request and display the result into the next tag?

I using jQuery and have the following code, it's a partial and I want to know how could I retrieve a specific data on the onchange method and display the result into the next tag. (inside the span tag)
NOTE: this select field are generated on-the-fly, so, I can have N id's.
<p class="fields">
<%= f.collection_select(:part_id, #parts, :id, :title, { :prompt => true } , { :onchange => "?" } ) %>
<span class='part_price'> _ _ _ _ </span>
<%= f.hidden_field :_destroy %>
<%= link_to_remove_fields "remove", f %>
</p>
Also I've created the method for this action (I don't know if this is right):
def retrieve_part_price
#price = Part.find(params[:id])
respond_to do |format|
format.html { redirect_to(items_path)}
format.json { render #price }
end
end
And put that on the routes.rb:
resources :items do
member do
get :update_part_price
end
end
Solved.
my partial:
<p class="fields">
<%= f.collection_select(:part_id, #parts, :id, :title, { :prompt => true } , { :onchange => "load_part_price_select(this.id, this.options[this.selectedIndex].value);" } ) %>
<%= f.label(:part_id, "Price: ") %>
<span class="price"></span>
<%= f.hidden_field :_destroy %>
<%= link_to_remove_fields "remove", f %>
</p>
application.js
function load_part_price_select(id, value) {
$('#' + id ).live('change',function() {
$.ajax({
url: '/parts/' + value + '/price',
type: 'get',
context: this,
dataType: 'script',
success: function(responseData) {
$(this).nextAll("span.price:first").html(responseData);
}
});
});
};
controller:
def price
#price = Part.find(params[:id])
respond_to do |format|
format.js { render :text => #price.price }
end
end

Rails 3 Switch menu reload page when change data

The user can edit his account and has a menu to choose his community :
<%= form_for #user, :html => { :multipart => true } do |f| %>
<%= f.collection_select :community_id, Community.find(:all,
:include => :memberships,
:conditions => ['memberships.user_id = ? and memberships.role > ?', #user.id, '0' ]),
:id,
:name,
:style => "width: 200px;" %>
<% end %>
I would like to put this menu on the show page and give him the possibility to switch directly.
With rails 2, I used observe_field or :onchange => 'this.form.onsubmit()' and I don't know java…
<%= form_for #user, :remote => true do |f| %>
<%= f.collection_select :community_id,
Community.where('memberships.user_id = ? and memberships.role > ?', #user.id, '0').includes(:memberships), :id, :name,{},
:onchange => "this.form.submit();" %>
<% end %>
Changed 'this.form.onsubmit() to 'this.form.submit()